要求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否充足,够就直接扣款,不够就提醒
- 可随时推出,退出时打印以购买商品,购买商品数量及余额
代码:
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<&#61;choice_of_user<len(list_of_goods):
32
33 #判断余额是否足够买此商品
34 if list_of_goods[choice_of_user][1]<&#61;salary:
35
36 #加入购物清单
37 list_of_bought.append(list_of_goods[choice_of_user][0])
38
39 #计算余额&#96;
40 salary-&#61;list_of_goods[choice_of_user][1]
41
42 print(&#39;&#39;&#39;添加{boughtgood}到您的购物车,此刻您的余额为{balance}.
43 &#39;&#39;&#39;.format(boughtgood&#61;list_of_goods[choice_of_user][0],balance&#61;salary))
44 else:
45 print(&#39;您的余额不足,此实余额为%s,不够购买此商品&#39;,salary)
46 else:
47 print(&#39;商品不存在&#39;)
48
49 elif choice_of_user&#61;&#61;&#39;q&#39;:
50
51 #统计购买的商品及数量
52 category_of_bought&#61;set(list_of_bought)
53 for item in category_of_bought:
54 dict_of_bought[item]&#61;list_of_bought.count(item)
55 print(&#39;您购买的商品及数量分别为&#39;,dict_of_bought)
56
57 print(&#39;您的余额为:&#39;,salary)
58 exit()
59 else:
60 print(&#39;输入不合法&#39;)
61 else:
62 print(&#39;输入不合法&#39;)