Python 实例2—购物车
老男孩教学学习笔记
"""
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随机退出,退出时,打印已购买商品和余额
"""
思路
"""
定义一个商品列表;
定义一个空列表,用于存放用户已买商品;
判断
"""
1 proc_list = [ 2 ("Iphone", 6300), 3 ("Mac pro", 12000), 4 ("star_coffie", 50), 5 ("python_book", 68), 6 ("Bike", 800), 7 ("Tesla", 1320000) 8 ] 9 10 shopping_list = [] 11 money = input("please input your money: ") 12 if money.isdigit(): 13 salary = int(money) 14 # print(salary) 15 while True: 16 for index, item in enumerate(proc_list): 17 print(index, item) 18 19 user_choice = input("选择要买什么?>>>") 20 if user_choice.isdigit(): 21 user_choice = int(user_choice) 22 if user_choice < len(proc_list) and user_choice >= 0: 23 p_item = proc_list[user_choice] 24 if p_item[1] <= salary: 25 shopping_list.append(p_item) 26 salary -= p_item[1] 27 print("Added \033[32;1m%s\033[0m into shopping cart, your current balance is \033[31;1m%s\033[0m " % (p_item, salary)) 28 else: 29 print("\033[41;1m您的余额不足%s,请重新选择: \033[0m " % salary) 30 else: 31 print("\033[41;1m该商品不存在,请重新输入:\033[0m") 32 elif user_choice == "q": 33 print("------------ shopping list ------------") 34 for p in shopping_list: 35 print(p) 36 print("\n your current balance %s" % salary) 37 exit() 38 else: 39 print("\033[041;1m Invalid input \033[0m") 40 41 else: 42 print("\033[041;1m Invalid input \033[0m")
购物车优化:
用户入口:
1、商品信息存在文件里;
2、已购商品,余额记录;
商家入口:
1、可以添加商品,修改商品价格
浙公网安备 33010602011771号