Python 购物车程序练习

 1 #author F
 2 
 3 import sys
 4 
 5 #list格式存储商品信息
 6 product_list = [
 7     ('Iphone', 5800),
 8     ('MacPro', 10000),
 9     ('Bike', 888),
10     ('Watch', 2300),
11     ('Coffee', 58),
12     ('Mouse', 158)
13 ]
14 shopping_list = []
15 salary = input("input your salary:")
16 if salary.isdigit():
17     salary = int(salary)
18     while True:
19         for index, item in enumerate(product_list):# enumerate:把下标取出
20             print(index, item)
21         user_choose = input("要买什么呢?")
22         if user_choose.isdigit():
23             user_choose = int(user_choose)
24             if 0 <= user_choose < len(product_list):
25                 p_item = product_list[user_choose]
26                 if p_item[1] <= salary:#买得起
27                     shopping_list.append(p_item)
28                     salary -= p_item[1]
29                     print("Added {item} into your cart and your balance is {balance}".format(item=p_item, balance=salary))
30                 else:
31                     print("你的余额只剩下[%s]啦,还买个毛线啊" % salary)
32             else:
33                 print("goods do not exists")
34         elif user_choose == 'q':
35             print("------shopping list------")
36             for p in shopping_list:
37                 print(p)
38             print("Your current balance:", salary)
39             sys.exit() #不引入sys会报错
40         else:
41             print("invalid option")

 

posted @ 2017-06-08 11:12  Bird_getUpEarly  阅读(160)  评论(0编辑  收藏  举报