python实现购物车小程序

Rosalia ·
更新时间:2024-09-20
· 203 次阅读

本文实例为大家分享了python实现购物车小程序的具体代码,供大家参考,具体内容如下

功能实现:

(1)可以查看购物车的商品,和余额

(2)可以显示商品列表,根据商品的编号选择商品

#定义一个列表存放商品信息 products=[('iphone',5800),('bike',220),('vivo',2000),('book',20)] shopping_list=[]#将购买的商品存在列表shopping_list 中 salary=input("输入你的工资") #判断输入的工资是否是数字 if salary.isdigit():     salary=int(salary)#把输入的工资转换为整型     while True:         # for i in products:输出商品编号和商品信息两种方式均可         #     print(products.index(i),i)         for index,i in enumerate(products):             print(index,i)         user_choice=input("选择要买的商品")         #通过输入商品编号来选择商品         if user_choice.isdigit():             user_choice=int(user_choice)             if user_choice>=0 and user_choice<len(products):                 p_item=products[user_choice]                 if p_item[1]<=salary:                     shopping_list.append(p_item)#把买的东西放到购物车                     salary-=p_item[1]#计算买完东西以后剩下的钱                     print("add %s into shopping car,you current salary %s" %(p_item[0],salary))                 else:                     print("\033[41;1m你的余额只剩[%s]了,不能买了,按q退出\033[0m" %salary)             else:                 print("商品不存在")         elif user_choice=='q':             print("购物车的商品如下所示")             for p in shopping_list:                 print(p)             print("余额",salary)             break         else:             print("invalid input") else:     print("invalid input")

效果:



小程序 程序 购物车 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号