1 # Author: Jason Zhu
2
3 '''
4 需求:
5 1. 启动程序后,让用户输入工资,然后打印商品列表
6 2. 允许用户根据商品编号购买商品
7 3. 用户选择商品后,检测余额是否充足,是就直接购买,否则就提示-您余额不足。
8 4. 可随时退出程序,退出时,打印已经购买的商品和您当前账户的余额
9 '''
10
11 product_list = [
12 ('小米手机',3999),
13 ('三星冰箱',12999),
14 ('罗技键盘',998),
15 ('Python工具书',52)
16 ]
17
18 shopping_list =[]
19 salary = input('请输入您的工资>>')
20 if salary.isdigit(): # 判断输入是否为 数字
21 salary = int(salary)
22 while True:
23 for num,item in enumerate(product_list):
24 print(num,item)
25
26 user_choice = input('选择您要购买的商品编号>>')
27 if user_choice.isdigit():
28 user_choice = int(user_choice)
29 if user_choice < len(product_list) and user_choice >=0:
30 p_item = product_list[user_choice]
31 if p_item[1] <= salary:
32 shopping_list.append(p_item)
33 salary-=p_item[1]
34 print('您购买了\033[32;1m[%s]\033[0m,当前账户余额为\033[32;1m%s元\033[0m'%(p_item[0],salary))
35 else:
36 print('\033[41;1m您余额只有[%s元],还买个毛线\033[0m'% salary)
37 else:
38 print('\033[41;1m商品编号不存在,请输入正确的商品编号\033[0m')
39 elif user_choice == 'q': # 程序退出
40 print('-------您的购物清单如下----------')
41 for p in shopping_list:
42 print(p)
43 print('您当前\033[31;1m余额\033[0m还有\033[31;1m[%s元]\033[0m'% salary)
44 exit()
45 else:
46 print('输入有误,请重新输入')
来源:oschina
链接:https://my.oschina.net/u/4340589/blog/3226632