要求:1.用户输入工资后展示商品列表2.根据商品编号选择商品3.选择商品后打印商品清单以及剩余工资代码如下:# coding=utf-8product_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")
原文地址:https://www.cnblogs.com/guoyanxia/p/8995299.html
时间: 2024-11-05 18:54:32