好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

python实现购物车小程序

本文实例为大家分享了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实现购物车小程序的详细内容...

  阅读:42次