购物车(2)优化代码

xiaoxiao2021-02-28  128

优化,更改为使用列表

# -*- coding: utf-8 -*- # @Author: oppend # @Date: 2017-07-27 19:43:59 # @Last Modified by: oppend # @Last Modified time: 2017-07-27 23:08:16 product_list = [('bike',1500),('tea',80),('computer',3500),('book',130)] my_amount = input('您的资金(元):') shopping_car = {} shopcar = shopping_car.keys() while True: print('>>>>>>>>>>>>商品列表<<<<<<<<<<<') for num,product in enumerate(product_list,1): print('[',num,']','=>','{0:<10}{1:>12}'.format(product[0],product[1])) print('-------------end---------------') choice = input('输入购买商品序号[q:退出]:') # 序号输入是否为数字 if choice.isdigit(): choice = int(choice)-1 my_amount = int(my_amount) # 序号选择是否超出范围 if 0 <= choice < len(product_list): choice_product = product_list[choice] product_name = str(choice_product[0]) product_price = int(choice_product[1]) # 金额是否足够 if my_amount >= product_price: # 购物车是否存在商品 if product_name not in shopcar: shopping_car[product_name] = [product_price,1] else: total = shopping_car[product_name][0] * 2 count = shopping_car[product_name][1] + 1 shopping_car[product_name] = [total,count] # 计算余额 balane = my_amount - product_price print('购买了{0}x1,剩余金额{1}'.format(product_name,balane)) my_amount = balane else: print('余额不足!') continue else: print('商品序号[{0}]不存在!'.format(choice+1)) continue elif choice.lower() == 'q': if len(shopping_car) > 0: print('==========您已购买=========') for name in shopcar: price = shopping_car[name][0] product_num = shopping_car[name][1] print('{0:<10}{1:<15}x{2}'.format(name,price,product_num)) print('===========================') break else: print('商品序号[{0}]错误!'.format(choice)) continue
转载请注明原文地址: https://www.6miu.com/read-32192.html

最新回复(0)