首页 > 技术文章 > python-购物车小程序

archerzon 2018-08-16 12:31 原文

原理:列表,元组,while循环,isdigit,for循环,enumerate用法,if语句的套用,

 1 #Author:Archer Zon
 2 product_list = [
 3     ('iphone', 5800),
 4     ('Mac Pro', 10800),
 5     ('Bike', 800),
 6     ('coffee', 31),
 7     ('Watch', 9800),
 8     ('Archer Python', 120)
 9 ]
10 salary = input("You salary is:")
11 shopping_list = []
12 if salary.isdigit():
13     salary = int(salary)
14     while True:
15         for index,item in enumerate(product_list):
16             print(index,item)
17         user_choice = input("选择你要购买的东西>>>...:")
18         if user_choice.isdigit():
19             user_choice = int(user_choice)
20             if user_choice < len(product_list) and user_choice >= 0:
21                 p_item = product_list[user_choice]
22                 if p_item[1] < salary:
23                     shopping_list.append(p_item)
24                     salary -= p_item[1]
25                     print("You have bought \033[31;1m%s\033[0m.You current balance is \033[31;1m%s\033[0m"%(p_item[0],salary))
26                 else:
27                     print("你的余额不足!只剩%s,请充钱!"%salary)
28             else:
29                 print("Your product code [%s] is not exit!"%user_choice)
30         elif user_choice == 'q':
31             print("-----shopping_list-----")
32             for p in shopping_list:
33                 print(p)
34             print("Your current balance is \033[31;1m%s\033[0m"%salary)
35             exit()
36         else:
37             print("invalid option!")
38 else:
39     print("invalid option!")
View Code

商品菜单使用列表,便于增删改查。列表里里面的商品使用元组,因为商品和商品价格必须一一对应,且取到商品后可以用p_item[0]获得商品名称,用p_item[1]获得商品价格。

 

推荐阅读