要求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否充足,够就直接扣款,不够就提醒
- 可随时推出,退出时打印以购买商品,购买商品数量及余额
代码:
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:James Tao 4 5 list_of_goods=[ 6 [‘iphone‘,5800], 7 [‘Mac Pro‘,12000], 8 [‘Bike‘,800], 9 [‘Watch‘,2000], 10 [‘Coffee‘,31], 11 [‘Book‘,120] 12 ] 13 list_of_bought=[] 14 dict_of_bought={} 15 salary=input(‘请输入您的工资:‘) 16 if salary.isdigit():#判断是否是整数 17 salary=int(salary) 18 while True: 19 20 #输出商品及其编号 21 for index,item in enumerate(list_of_goods):#enumerate取出下标 22 print(index,item) 23 #print(list_of_goods.index(item),item) 24 choice_of_user=input(‘选择购买商品编号:‘) 25 26 #判断输入是否合法 27 if choice_of_user.isdigit(): 28 choice_of_user=int(choice_of_user) 29 30 #判断编号是否有对应商品 31 if 0<=choice_of_user<len(list_of_goods): 32 33 #判断余额是否足够买此商品 34 if list_of_goods[choice_of_user][1]<=salary: 35 36 #加入购物清单 37 list_of_bought.append(list_of_goods[choice_of_user][0]) 38 39 #计算余额` 40 salary-=list_of_goods[choice_of_user][1] 41 42 print(‘‘‘添加{boughtgood}到您的购物车,此刻您的余额为{balance}. 43 ‘‘‘.format(boughtgood=list_of_goods[choice_of_user][0],balance=salary)) 44 else: 45 print(‘您的余额不足,此实余额为%s,不够购买此商品‘,salary) 46 else: 47 print(‘商品不存在‘) 48 49 elif choice_of_user==‘q‘: 50 51 #统计购买的商品及数量 52 category_of_bought=set(list_of_bought) 53 for item in category_of_bought: 54 dict_of_bought[item]=list_of_bought.count(item) 55 print(‘您购买的商品及数量分别为‘,dict_of_bought) 56 57 print(‘您的余额为:‘,salary) 58 exit() 59 else: 60 print(‘输入不合法‘) 61 else: 62 print(‘输入不合法‘)
原文地址:https://www.cnblogs.com/BIT-taozhen/p/9735865.html
时间: 2024-10-10 01:22:57