python购物车
# 购物 produce = [ {'name': 'apple', 'price': '20'}, {'name': 'mi', 'price': '30'}, {'name': 'mac', 'price': '15'} ] shopping_car = {} exit_flag = False print("----------商品列表----------") money = int(input("看我看看你的钱:").strip()) # if money.isdigit(): # money = int(money) # else: # print("请重让我看看你的钱!!") # money = input("看我看看你的钱").strip() while not exit_flag: for index, i in enumerate(produce): print('序号{},\t商品:{},\t价格:{}'.format(index, i['name'], i['price'])) choice = input("请选择你要购买产品的序号:") if choice.isdigit(): choice = int(choice) if 0 <= choice < len(produce): # 这里不推荐这么写,为了pycharm不出警告 num = input("你要购买商品的数量:") money = money - int(produce[choice]['price'])*int(num) if money >= 0: # shopping_car.append(produce[choice]['name']) # shopping_car[produce[choice]['name']] = num
if produce[choice]['name'] in shopping_car:
shopping_car[produce[choice]['name']] += int(num)
else:
shopping_car[produce[choice]['name']] = int(num)
# print("你购买的商品数量为%d" % len(shopping_car)) for k, v in shopping_car.items(): print('购买商品:{},\t数量:{}'.format(k, v)) print('余额%d' % money) else: print("穷鬼,回家拿钱去吧!!") break elif choice.upper() == 'Q': for k, v in shopping_car.items(): print('购买商品:{},\t数量:{}'.format(k, v)) print('余额%d' % money) exit_flag = True else: print("请选择产品的序号!!")
还可以优化通过while判断money、num
# 购物改进 produce = [ {'name': 'apple', 'price': '20'}, {'name': 'mi', 'price': '30'}, {'name': 'mac', 'price': '15'} ] shopping_car = {} exit_flag = False print("----------商品列表----------") while not exit_flag: money = input("看我看看你的钱:").strip() if money.isdigit(): # 对用户输入的money进行出来 money = int(money) break # 结束当前循环 else: print("请重让我看看你的钱!!") # money = input("看我看看你的钱").strip() while not exit_flag: for index, i in enumerate(produce): print('序号{},\t商品:{},\t价格:{}'.format(index, i['name'], i['price'])) choice = input("请选择你要购买产品的序号:") if choice.isdigit(): choice = int(choice) if 0 <= choice < len(produce): # 这里不推荐这么写,为了pycharm不出警告 while not exit_flag: num = input("你要购买商品的数量:").strip() if num.isdigit(): # 对用户输入的num进行处理 break else: print("请重新输入购买数量,靓仔!!!") money = money - int(produce[choice]['price'])*int(num) if money >= 0: # shopping_car.append(produce[choice]['name']) shopping_car[produce[choice]['name']] = num # print("你购买的商品数量为%d" % len(shopping_car)) for k, v in shopping_car.items(): print('购买商品:{},\t数量:{}'.format(k, v)) print('余额%d' % money) else: print("穷鬼,回家拿钱去吧!!") break elif choice.upper() == 'Q': for k, v in shopping_car.items(): print('购买商品:{},\t数量:{}'.format(k, v)) print('余额%d' % money) exit_flag = True else: print("请选择产品的序号!!")