Python学习——购物车程序

问题需求:

1、启动程序,让用户输入工资,然后打印商品列表

2、允许用户根据商品编号购买商品

3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒

4、可随时退出,退出时,打印已购买的商品和余额

 1 __author__ = 'jcx'
 2 
 3 product_list = [
 4     ('iphone11',5000),
 5     ('macbook pro',9800),
 6     ('Bike',800),
 7     ('Coffee',31),
 8     ('jcx\'s C++',60),
 9 ]
10 
11 shoping_list = []
12 salary = input("Input your salary: ")
13 if salary.isdigit():
14     salary = int(salary)
15     while True:
16         for index,item in enumerate(product_list):
17             print(index,item)
18         user_choice = input("选择要买的商品>>>: ")
19         if user_choice.isdigit():
20             user_choice = int(user_choice)
21             if user_choice < len(product_list) and user_choice >= 0:
22                 p_item = product_list[user_choice]
23                 if p_item[1] <= salary: #买得起
24                     shoping_list.append(p_item)
25                     salary -= p_item[1]
26                     print("Added %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % (p_item,salary))
27                 else:
28                     print("\033[41;1m你的余额只剩[%s]\033[0m" % salary)
29             else:
30                 print("product number [%s] is not exist." % user_choice)
31         elif user_choice == 'q':
32             print("------  shoping list -------")
33             for p in shoping_list:
34                 print(p)
35             print("You current balance: \033[31;1m%s\033[0m" % salary)
36             exit()
37         else:
38             print("invalid option")

 输出结果:

 1 Input your salary: 6000
 2 0 ('iphone11', 5000)
 3 1 ('macbook pro', 9800)
 4 2 ('Bike', 800)
 5 3 ('Coffee', 31)
 6 4 ("jcx's C++", 60)
 7 选择要买的商品>>>: 0
 8 Added ('iphone11', 5000) into shopping cart, your current balance is 1000
 9 0 ('iphone11', 5000)
10 1 ('macbook pro', 9800)
11 2 ('Bike', 800)
12 3 ('Coffee', 31)
13 4 ("jcx's C++", 60)
14 选择要买的商品>>>: 6
15 product number [6] is not exist.
16 0 ('iphone11', 5000)
17 1 ('macbook pro', 9800)
18 2 ('Bike', 800)
19 3 ('Coffee', 31)
20 4 ("jcx's C++", 60)
21 选择要买的商品>>>: q
22 ------  shoping list -------
23 ('iphone11', 5000)
24 You current balance: 1000
25 
26 Process finished with exit code 0

猜你喜欢

转载自www.cnblogs.com/jcxioo/p/11586505.html