程序练习
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
#产品列表 product_list = [ ('Iphone',5800), ('Mac Pro', 9800), ('Bike', 800), ('Watch', 10600), ('Coffee', 31), ('Book', 120), ] #购物车列表 shopping_list = [] #输入工资 salary = input('input your salary:') #判断输出是否为数字 if salary.isdigit(): #是数字,继续 salary = int(salary) #将输入格式化成整型 while True: #循环 for item in product_list: #打印产品下表及物品 print(product_list.index(item),item) user_choice =input('buy what>>>:') 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('Added %s into shoppint cart ,your current balance is %s' %(p_item,salary)) else: print('\033[41;1m你的余额[%s]不足\033[0m'%salary) else: #大于列表数 print('商品不存在') elif user_choice=='q': #选择q退出程序 print('--------shoppint list---------') for p in shopping_list: print(p) print('You current balance',salary) exit() print('exit...') else: #不是数字,退出 print('Invalid option')