python购物车小程序

2018-06-18 02:45:08来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

要求:
1.用户输入工资后展示商品列表
2.根据商品编号选择商品
3.选择商品后打印商品清单以及剩余工资
代码如下:
# coding=utf-8
product_list = [
('iphone',5800),
('mac pro',9800),
('bike',800),
('watch',10600),
('coffee',31),
('Alex python',120),
]
shopping_list = []#购物车
salary = input("Input your salary:")
if salary.isdigit(): #判断工资是否为数字
salary = int(salary)
while True:
for index,item in enumerate(product_list):#enumerate--取下标
print(index,item)#打印商品列表
#取下标print(product_list.index(item),item)
user_choice = input("选择商品>>>:")
if user_choice.isdigit():#判断用户输入是否为数字
user_choice = int(user_choice)
if user_choice < len(product_list) and user_choice >=0:#判断用户输入的商品编号是否在下标范围之内,len()-取列表下标长度
p_item = product_list[user_choice]#通过下标获取商品价格

if p_item[1] <= salary:#买的起
shopping_list.append(p_item)#将该商品加到购物车
salary -= p_item[1]#扣钱
print("Added %s into shopping cart,your current banlance is \033[31;1m%s\033[0m"%(p_item ,salary))
else:#买不起
print("\033[41;1m你的余额只剩[%s]啦,买不起啦,你可选择其他商品或者输入‘q’退出\033[0m" % salary)
else:#输入编号不存在
print("商品不存在[%s]",user_choice)

elif user_choice == 'q':#退出
print("---------shopping list----------")#打印商品清单
for p in shopping_list:
print(p)
print("你的工资余额。。。",salary)
exit()
else:
print("invalid option")

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:将url中的中文转成Unicode编码

下一篇:【Python学习笔记】Coursera之PY4E学习笔记——String