1 #Author:ersa
2 ‘‘‘
3 程序:购物车程序
4
5 需求:
6
7 启动程序后,让用户输入工资,然后打印商品列表
8 允许用户根据商品编号购买商品
9 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
10 可随时退出,退出时,打印已购买商品和余额
11
12 #知识点:len(market):列表长度(列表中的条目个数)
13 isdigit() 判断输入的内容是否是数字,TRUE 是数字
14 取列表数据 enumerate
15 for index,item in enumerate(market)
16 print(index, item)
17 输出内容高亮显示 "\033[31;1m%s\033[0m"%(balance)
18 退出程序使用exit()方法
19 ‘‘‘
20
21 market = [[1,"iphone",5800],
22 [2,"Mac Pro", 12000],
23 [3,"Starbuck Latte",31],
24 [4,"Alex Python",88],
25 [5,"bike",1800]]
26
27 balance = input("please input salary: ")
28 if balance.isdigit():
29 balance = int(balance)
30 else:
31 exit("Illegal value, please re-enter")
32
33 amount = 0
34 print("Tip: type q to exit.\n\n")
35
36 shopping_cart = []
37 while True:
38 for commodity in market:
39 print(commodity)
40
41 user_choice = input("Please enter a product number or q:\n")
42
43 if user_choice == "q":
44 break
45
46 if user_choice.isdigit():
47 user_choice = int(user_choice)
48 if 0 and user_choice <= (len(market)+1):
49 amount += market[user_choice - 1][2];
50 if balance < amount:
51 print("Reminder: the balance is insufficient, please re-purchase.\n")
52 continue
53 shopping_cart.append(market[user_choice - 1])
54 else:
55 print("If you do not have this item, please reselect it !\n")
56 continue
57
58 print("List of purchased items:\n")
59 for commodity in shopping_cart:
60 print(commodity)
61 print("Payment amount: \033[41;1m%s\033[0m"%(amount))
62 balance -= amount
63 print("your balance: \033[31;1m%s\033[0m \n"%balance)