‘‘‘购物车程序需求:1.启动程序后,让用户输入工资,然后打印商品列表2.允许用户根据商品编号购买商品3.用户选择商品后,检查余额是否够,够就直接扣款,不够就提醒4.用户可一直购买商品,也可随时退出,退出时,打印已购买商品和余额‘‘‘#商品列表products_list = [[‘Iphone8‘, 6888], [‘MacPro‘, 14800], [‘小米6‘, 2499], [‘Coffee‘, 31], [‘Book‘, 80], [‘Nike Shoes‘, 799]] print("欢迎来到中关村手机城!".center(50, "*"))#充值while True: salary = input("请输入您的工资: ").strip() if salary.isdigit(): salary = int(salary) print("恭喜您充值成功! 您的账号余额为: %d元." % salary) break else: print("输入有误! 请重新输入您正确的工资.") #总消费金额consume_total = 0#购买商品shopping_cart = {}while True: #显示商品信息 print("中关村手机城商品信息".center(50, "*")) print("商品序号\t商品名称\t商品价格") for ind, products in enumerate(products_list): print("%d\t\t\t%s\t\t%d" % (ind, products[0], products[1])) print("Q\t\t\t退出") #用户选择商品编号 user_choice = input("请输入您要购买的商品编号: ").strip() if user_choice.isdigit(): user_choice = int(user_choice) #添加购物车并结算 if user_choice >= 0 and user_choice < len(products_list): #余额足 if salary - consume_total - products_list[user_choice][1] >= 0: shopping_name = products_list[user_choice][0] shopping_price = products_list[user_choice][1] #判断商品是否已买过 if user_choice in shopping_cart: shopping_cart[user_choice][2] += 1 else: shopping_cart[user_choice] = [shopping_name, shopping_price, 1] consume_total += shopping_price print("恭喜您!成功购买商品: %s,本次消费: %d元. 总消费: %d元. 账号余额: %d元." % (shopping_name, shopping_price, consume_total, salary - consume_total)) #余额不足 else: print("余额不足! 已消费: %d元. 账号余额: %d元." % (consume_total, salary - consume_total)) else: print("商品不存在! 请重新选择.") elif user_choice.upper() == "Q": break else: print("商品不存在! 请重新选择.") #判断购物车是否为空if shopping_cart != {}: print("您已购买的商品信息".center(50, "*")) print("商品编号\t商品名称\t商品单价\t商品数量") for id, cars in shopping_cart.items(): print("%d\t\t\t%s\t\t%d\t\t\t%d" % (id, cars[0], cars[1], cars[2])) print("总消费: %d元, 账号余额: %d 元" % (consume_total, salary - consume_total)) print("欢迎下次光临!".center(50, "*"))
原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10681670.html
时间: 2024-11-02 21:18:51