1 # 简单的购物小程序
2
3 product_list = [
4 ['surface pro 4', 7800],
5 ['dell xps 15', 12000],
6 ['macbook', 12000],
7 ['小米6', 2499],
8 ['iphone7', 4600],
9 ['坚果Pro', 1499]
10 ]
11 shopping_list = []
12
13
14 # 判断输入的薪水格式是否正确
15 while True:
16 salary = input('\n请输入您的薪水:')
17 if not salary.isdigit(): # 薪水不是数字,结束循环
18 print('\n输入格式有误!请重新输入...')
19 continue
20 break
21
22
23 balance = salary = int(salary)
24
25 print('\n-----------欢迎购买------------\n')
26
27 # 生成带序号的商品列表
28 for index, item in enumerate(product_list):
29 print(index, item)
30
31
32 # 判断输入的序号是否符合要求
33 while True:
34
35 while True:
36 i = input('\n输入您要购买的商品序号,或输入 q 取消购买:')
37 if i == 'q': # 输入 q 退出购买界面
38 while True:
39 a = input('\n是否继续购买?(Y/N):')
40 if a != 'n' and a != 'N' and a != 'y' and a != 'Y':
41 print('\n输入格式有误,请重试...')
42 continue
43 elif a == 'y' or a == 'Y': # 继续购买
44 break
45 else: # 购买完毕
46 if balance == salary: # 没有买任何东西
47 print('\n交易结束,购买失败...')
48 exit()
49 else: # 结算
50 print('\n您已成功购买以下商品:\n')
51 for item in shopping_list:
52 print(item)
53 print('\n共消费金额 %d 元,余额 %d 元' % (salary - balance, balance))
54 exit()
55 continue
56
57 if not i.isdigit(): # 序号不是数字,结束循环
58 print('\n输入格式有误!请重新输入...')
59 continue
60
61 i = int(i)
62
63 if i < 0 or i >= len(product_list): # 序号范围不正确,结束循环
64 print('\n此商品不存在,请重新输入...')
65 continue
66 break
67
68 product = product_list[i]
69 price = int(product[1])
70
71 # 判断余额是否充足,够就直接扣款,不够提醒
72 if price <= balance:
73 balance -= price
74 shopping_list.append(product_list[i])
75 print('\n您已成功购买 %s ,当前余额为 %d 元' %(product, balance))
76 else:
77 print('\n购买失败,您的余额不足...')
78
79 while True:
80 a = input('\n是否继续购买?(Y/N):')
81 if a != 'n' and a != 'N' and a != 'y' and a != 'Y':
82 print('\n输入格式有误,请重试...')
83 continue
84 break
85
86 if a == 'Y' or a == 'y':
87 continue
88 else:
89 break
90
91 if balance == salary:
92 print('\n交易结束,购买失败...')
93 exit()
94 else:
95 print('\n您已成功购买以下商品:\n')
96 for item in shopping_list:
97 print(item)
98 print('\n共消费金额 %d 元,余额 %d 元' %(salary-balance, balance))
99 exit()