程序:
购物车程序
需求:
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
代码:
product_list=[ ('IPhone',5800), ('Mac Pro',21000), ('Starbuck Latte',31), ('Python boo)k',81), ('Bicycle',800) ] shopping_list=[] salary=input("your salary:") if salary.isdigit(): salary=int(salary) while True: print("----------product list----------") for index,item in enumerate(product_list): 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("Added %s into your shopping cart,your current balance is \033[32;1m%s\033[0m"%(p_item[0],salary)) #31显示红色,32显示绿色 else: print("\033[41;1m你的余额只剩%s,余额不足买不起哦\033[0m"%salary) #41表示红底高亮显示,42表示绿底高亮显示 else: print("商品编号不存在") elif user_choice == 'q': print("----------shopping list----------") for p in shopping_list: print(p) print("your current balance is %s"%salary) exit() else: print("Invalid Option!") else: print("Invalid Option!")