1 # _author : Ahern Li
2 # @_date : 2017/9/10
3
4 print('------ 欢迎进入购物车 ------')
5 # 购物车列表
6 shopping_cart = []
7 # 商品列表,商品价格具备修改功能,内嵌列表(字典)比元组更加灵活
8 goods= [['iphone6s',5800],['mac book',9000],['coffee',32],['python book',80],['bicyle',1500]]
9 # 判断输入是否合法
10 while True:
11 money = input('please input your money:')
12 if money.isdigit():
13 money = int(money)
14 break
15 else:
16 print('you should input a digit!\n')
17 # 空一行,执行界面更好看
18 print()
19 while True:
20 # 打印格式如 1 : iphone6s 5800
21 for i in goods:
22 x,y = i
23 print(str(goods.index(i)+1),':',x,y)
24 # 提示输入格式,及退出方式
25 choice = input('\n请输入商品序号(q,退出)\n>>>:')
26 # 判断输入是否合法
27 if choice.isdigit():
28 choice = int(choice)
29 if choice > 0 and choice <= len(goods):
30 # 判断余额是否充足
31 if money > goods[choice-1][1]:
32 # 加入购物车
33 shopping_cart.append(goods[choice-1])
34 # 余额
35 money -= goods[choice-1][1]
36 print('已加入%s到你的购物车,当余额:%d\n' % (goods[choice-1][0],money))
37 else:
38 print('余额不足,%d\n' % (money-goods[choice-1][1]))
39 else:
40 print('您输入的商品序号不存在!\n')
41 # 退出指令
42 elif choice == 'q':
43 break
44 else:
45 print('序号有误!重新输入。\n')
46 print('\n您已购买以下商品:')
47 # 循环遍历打印已购买商品
48 for i in shopping_cart:
49 x,y = i
50 print(x,y)
51 print('\n您的余额为:%d' % money)
52 print('\n------ 欢迎下次光临 ------')