程序:购物车程序
需求:
1、启动程序后,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
1 product_list = [ # 创建商品列表 2 ('iPhone', 5800), 3 ('Mac Pro', 9800), 4 ('Bike', 800), 5 ('Watch', 10600), 6 ('Coffee', 31), 7 ('Book Python', 120), 8 ] 9 shopping_list = [] # 创建购物列表 10 salary = input("Input you salary:") # 输入工资 11 12 if salary.isdigit(): # 如果薪水输入正确 13 salary = int(salary) # 转换为整数型 14 while True: # 循环选购商品 15 for index, item in enumerate(product_list): # 打印产品列表 16 print(index, item) 17 user_choice = input("选择你要购买的商品:") # 获取信息选择要买的商品还是退出 18 if user_choice.isdigit(): # 如果输入的是数字 19 user_choice = int(user_choice) 20 if user_choice < len(product_list) and user_choice >= 0: # 如果 0<= 数字 <6 21 p_item = product_list[user_choice] # 获取对应产品 22 if p_item[1] <= salary: # 如果买得起 23 shopping_list.append(p_item) # 添加入购物列表 24 salary -= p_item[1] # 计算余额 25 # 显示购买商品及余额 26 print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % (p_item, salary)) 27 else: 28 print("\033[41;1m你的余额只剩[%s].\033[0m" % salary) 29 else: # 如果非 0<= 数字 <6 30 print("product code [%s] is not exist!" % user_choice) 31 elif user_choice == 'q': # 如果输入的是Q 32 print("----------Shopping List----------") 33 for p in shopping_list: 34 print(p) 35 print("You current balance", salary) 36 exit() 37 else: 38 print("Invalid option") # 如果不是数字也不是Q 39 else: # 如果薪水输入错误 40 print("薪水输入错误,录入为:\033[31;1m%s\033[0m" % salary) 41 exit()