需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

代码实现:

 1 # 定义商品列表
 2 List_of_goods = [
 3     ("Computer", 3500),
 4     ("Bicycle", 800),
 5     ("Jhs python", 90),
 6     ("Robot", 12000),
 7     ("shoes", 50),
 8     ("Hamburger", 15),
 9 ]
10 
11 # 定义一个空购物车
12 Shopping_list = []
13 
14 # 输入你的工资-money
15 MyMoney = input("input yours wages: ")
16 
17 # 判断输入的字符串是否为数字
18 if MyMoney.isdigit():
19     
20     # 如果是数字,转换成int类型
21     MyMoney = int(MyMoney)
22     
23     # 定义一个while死循环
24     while 1:
25     
26         # 列出商品列表中的下标,当商品编号使用
27         for index, x in enumerate(List_of_goods):
28         
29             # 打印商品下标对应的商品
30             print(index, x)
31         
32         # 请用户输入商品编号,就是上面的商品对应的下标
33         count = input("Please enter the commodity number: ")
34         
35         # 判断输入的商品编号是否是数字
36         if count.isdigit():
37             
38             # 是数字转换为int类型
39             count = int(count)
40 
41             # 判断商品列表中编号是否存在
42             if count < len(List_of_goods) and count >=0:
43                 
44                 # 通过下标取出商品
45                 p_subscript = List_of_goods[count]
46                 
47                 # 买得起   价格小于输入的工资
48                 if p_subscript[1] <= MyMoney:
49     
50                     # 加到购物车列表
51                     Shopping_list.append(p_subscript)
52 
53                     # 扣钱
54                     MyMoney -= p_subscript[1]
55                     print("Added %s into shopping cart,your current balance is %s" % (p_subscript, MyMoney))
56                 
57                 # 买不起,商品价格大于工资     
58                 else:
59 
60                 # 返回结果
61                     print("Your balance is only %s, and buy a wool." % MyMoney)
62 
63             # 如果超出商品个数,则打印商品不存在
64             else:
65                 print("The goods you entered %d do not exist." % count)
66 
67         # q退出,打印购买的整个商品
68         elif count == "q":
69             print("------- shopping list -------")
70             for x in Shopping_list:
71                 print(x)
72             print("Your current balance: ", MyMoney)
73             exit()
74            
75         # 如果输入非数字,及q,提示无效选项
76         else:
77             print("invalid option")

 

posted on 2018-11-13 16:50  人生苦短;我用python  阅读(109)  评论(0编辑  收藏  举报