1 #!/usr/bin/ven python
2 # Author: Hawkeye
3 '''
4 本程序为实例程序:购物车程序
5
6 需求:
7
8 启动程序后,让用户输入工资,然后打印商品列表
9 允许用户根据商品编号购买商品
10 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
11 可随时退出,退出时,打印已购买商品和余额
12
13 '''
14 #创建商品列表
15 product_list = [
16 ["Iphone",5800],
17 ["Mac Pro",9800],
18 ["bike",800],
19 ["watch",10600],
20 ["coffee",31],
21 ["Alex Python",20]
22 ]
23 # for i in product_list:
24 # print(i)
25
26 #创建购物列表
27 shopping_list =[]
28 #要求用户输入数据
29 salary = input("Input your salary:")
30 #首先要对用户的输入做判断
31 if salary.isdigit():
32 salary = int(salary) #转换为整形
33 while True: #循环输出列表
34 for index,item in enumerate(product_list):
35 print(index,item)
36 user_choice = input("请选择要买什么......")
37 if user_choice.isdigit():#转换为整形
38 user_choice =int(user_choice)
39 if user_choice < len(product_list) and user_choice >=0:
40 p_item = product_list[user_choice]
41 if p_item[1] <=salary:#钱够
42 shopping_list.append(p_item)
43 salary -= p_item[1]
44 print("Added %s into shopping cart,your current balance is \033[31;1m%s\033[0m" % (p_item,salary) )
45 else:#钱不够
46 print("\033[41;1m您的余额只剩【%s】,余额不足\033[0m" %salary)
47 else:
48 print("\033[32;1mProduct code [%s]is not exist\033[0m " %user_choice)
49 elif user_choice == "q":
50
51 print("----------shoppig list--------")
52 for p in shopping_list:
53 print(p)
54 print("------------------------------")
55 print("\033[33;1mYour current balance is :\033[0m",salary)
56 exit()
57 else:
58 print("Invalid Option")
59 else:#输入q退出
60 print("\033[13;1m【错误】请输入正确的数字!\033[0m")
61 exit()