python购物车功能

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额
 1 product_list = [
 2     ('Iphone',6000),
 3     ('Watch', 2000),
 4     ('Bike',1000),
 5     ('Book',80),
 6     ('Coffee',30),
 7 ]
 8 shopping_list = []
 9 while True:
10     salary = input("你有多少工资:")
11     if salary.isdigit():
12         salary = int(salary)
13         while True:
14             #循环打印出商品列表
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                 #判断输入的序列号是否存在
21                 if user_choice < len(product_list) and user_choice >= 0:
22                     p_item = product_list[user_choice]
23                     #判断钱是否足够
24                     if salary >= p_item[1]: #买得起
25                         shopping_list.append(p_item)
26                         salary -= p_item[1]
27                         print("添加%s到购物车成功,你的余额还剩%s" %(p_item,salary))
28                     else:
29                         print("余额不足")
30                 else:
31                     print("输入错误,您选择的商品不存在")
32             elif user_choice == 'q':
33                 print("--------shopplist-----------")
34                 for p in shopping_list:
35                     print(p)
36                 print("您的余额为%s"%(salary))
37                 exit()
38             else:
39                 print('输入错误')
40     else:
41         print("请输入数字")
View Code

注意:

isdigit()判断用户输入的是否为数字
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

enumerate(sequence, [start=0])
参数:

sequence -- 一个序列、迭代器或其他支持迭代对象。

start -- 下标起始位置。

例子:
1 >>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
2 >>> list(enumerate(seasons))
3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
4 >>> list(enumerate(seasons, start=1))       # 下标从 1 开始
5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
View Code

猜你喜欢

转载自www.cnblogs.com/xifeng59/p/11649443.html