购物车程序

需求:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

提示:

1.enumeratie()函数用法,用于遍历序列中的元素以及它们的下标

1 names=["a", 'b', 'c', 'd']
2 for i,ele in enumerate(names):
3     print(i,ele)
0 a
1 b
2 c
3 d

2.列表的嵌套

1 products=[ ['a',1], ['b',2], ['c',3] ]
2 for i,ele in enumerate(products):
3     print(i,ele[0],ele[1])
0 a 1
1 b 2
2 c 3
 1 products = [
 2     ["Ipone",5800],
 3     ["Mac",15800],
 4     ["Coffee",30],
 5     ["Bike",2000],
 6     ["Cloth",500],
 7 ]
 8 shopping_list = []
 9 
10 
11 while True:
12     salary = input("Your salary:")
13     if salary.isdigit():
14         salary = int(salary)
15         break
16     else:
17         continue
18 
19 while True:
20     print("product list".center(50,"-"))
21     for index,i in enumerate(products):
22         print(index,".",i[0],i[1])
23     choice = input("请输入商品编号[quit]>>:")
24     if choice.isdigit():
25         choice = int(choice)
26         if choice >=0 and choice < len(products):
27             #判读钱够不够
28             p = products[choice]
29             if salary >= p[1]:#买的起
30                 salary -= p[1] #扣钱
31                 shopping_list.append(p) #加入购物车
32                 print("Added 33[32;1m[%s]33[0m into your shopping cart,and your current balance is 33[41;1m%s33[0m" %(p[0],salary))
33             else:
34                 print("钱不够,你只有[%s]" % salary)
35         else:
36             print("没有此商品...")
37     elif choice == "quit":
38         print("已购买商品".center(50,"-"))
39         for i in shopping_list:
40             print(i[0])
41         print("Your left balance is ", salary)
42         exit()
原文地址:https://www.cnblogs.com/wangmo/p/5975153.html