购物车程序:python
需求:git
1.启动程序后,让用户输入工资,而后打印商品列表app
2.容许用户根据商品编号购买商品iphone
3.用户选择商品后,监测余额是否够,够就直接扣款,不够就提醒ide
4.可随时退出,退出时,打印已购买商品和余额spa
#!/usr/bin/env python # -*- coding:utf-8 -*- shopping_list = [] # 购物车 product_list = [ # 商品清单 ('iphone', 5800), ('mac pro', 9800), ('bike', 800), ('watch', 10600), ('coffee', 31), ('xcn python', 120), ] salary = input("你的工资是多少:") if salary.isdigit(): # 判断输入是否为数字 salary = int(salary) while True: for index, item in enumerate(product_list): # 现实下标(index)根据下标购买物品 print(index, item) user_choice = input("要买啥:") if user_choice.isdigit(): user_choice = int(user_choice) if user_choice < len(product_list) and user_choice >=0: p_item = product_list[user_choice] if p_item[1] <= salary: # 买的价格小于工资,说明能买起 shopping_list.append(p_item) salary -= p_item[1] print("购买的物品:%s,余额:%s" % (p_item, salary)) else: print("余额不足") elif user_choice == 'q': print("----------shopping list------------") for p in shopping_list: print(p) print("如今余额:", salary) exit("欢迎下次光临") else: print("很差意思,商品已下架!")
注释:ip
len(product_list) #表示product_list下标最大值