购物车

一、购物车1.0
需求:
(1)打印产品列表里的产品
(2)写一个循环不断问用户想买什么,用户选择一个商品编号,把对应的商品编号添加到购物车,打印购物车里的商品列表


代码:

 1 # __author__ = "wyb"
 2 # date: 2018/4/7
 3 # 需求:
 4 # (1)打印产品列表里的产品
 5 # (2)写一个循环不断问用户想买什么,用户选择一个商品编号,
 6 # 把对应的商品编号添加到购物车,打印购物车里的商品列表
 7 
 8 # 产品列表:
 9 products = [['IPhone8', 6888], ['MacPro', 14688], ['Coffee', 21], ['book', 41], ['Nike Shoes', 999]]
10 
11 # 购物车中的商品列表:
12 shopping_car = []
13 
14 while True:
15     # 打印商品列表:
16     print("商品列表".center(30, '-'))
17     for index, p in enumerate(products):
18         print("%s: %s   %s" % (index, p[0], p[1]))
19 
20     # 输入及输入处理及输出购物车里的商品列表:
21     # 输入:
22     choice = input("输入想购买的物品(输入q退出): ")
23     # 退出:
24     if choice == 'q' or choice == 'Q':
25         # 输出购物车里的商品列表:
26         if shopping_car is []:
27             print("您没有购买任何商品")
28         else:
29             print("您购买了以下的商品".center(30, '-'))
30             for index, p in enumerate(shopping_car):
31                 print("%s: %s   %s" % (index, p[0], p[1]))
32         break
33     # 输入处理:
34     # 是数字:
35     elif choice.isdigit():
36         choice = int(choice)
37         if choice >= len(products) or choice < 0:
38             print("请输入正确的序号!")
39             continue
40     # 不是数字:
41     else:
42         print("请输入数字序号!")
43         continue
44 
45     # 向购物车中添加商品:
46     shopping_car.append(products[choice])
47     print("Add product %s into the shopping car" % (products[choice]))

二、购物车2.0

基础需求:

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

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

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

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

5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示

:  基础需求中的高亮显示可见我的另外一篇博客:  http://www.cnblogs.com/wyb666/p/8850276.html

扩展需求:

1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买

2、允许查询之前的消费记录

数据结构:

1 goods = [
2 {"name": "电脑", "price": 1999},
3 {"name": "鼠标", "price": 10},
4 {"name": "游艇", "price": 20},
5 {"name": "美女", "price": 998},
6 ......
7 ]

代码:

基础需求实现:

  1 # 用户信息
  2 user_info = {
  3     'wyb': '666',
  4 }
  5 
  6 # 商品列表
  7 goods = [
  8     {"name": "电脑", "price": 1999},
  9     {"name": "鼠标", "price": 10},
 10     {"name": "游艇", "price": 20},
 11     {"name": "美女", "price": 998},
 12 ]
 13 
 14 # 购物车列表 -> [{"name": "电脑", "price": 1999, "number": 1}...]
 15 shopping_cart = []
 16 
 17 
 18 # 高亮输出字符串
 19 def output_highlight(s):
 20     print('33[1;31;40m%s33[0m' % s)
 21 
 22 
 23 # 打印商品列表
 24 def output_info():
 25     print("info".center(36, '*'))
 26     print("		%s	%s" % ("name", "price"))
 27     for index, item in enumerate(goods):
 28         print("	%d.  %s		%d " % (index+1, item['name'], item['price']))
 29     print("end".center(36, '*'))
 30 
 31 
 32 # 退出时打印易购买商品和余额
 33 def output_shopping_salary():
 34     output_highlight('		你还剩下: %d元33[0m' % salary)
 35     print("shopping_cart".center(36, '-'))
 36     print("		%s	%s	%s" % ("name", "price", "number"))
 37     for index, item in enumerate(shopping_cart):
 38         print("%5d.%4s%8d%8d " % (index + 1, item['name'], item['price'], item['number']))
 39     print("end".center(36, '-'))
 40 
 41 
 42 # 选择函数,专门负责输入处理
 43 def input_choice(string):
 44     choices = input(string).strip()
 45     if choices == 'q':
 46         # 退出时,打印已购买商品和余额
 47         output_shopping_salary()
 48         exit()
 49 
 50     return choices
 51 
 52 
 53 # 登录验证程序:
 54 def login():
 55     count = 0
 56     while True:
 57         count += 1
 58         username = input_choice("username: ")
 59         password = input_choice("password: ")
 60         # 当输入3次并且第3次也错误的情况下用户不能再登录
 61         if count >= 3 and user_info.get(username, None) != password:
 62             print("你已经错了太多次了!不能再试了!")
 63             exit()
 64         if user_info.get(username, None) == password:
 65             print("登录成功!")
 66             return 0
 67         else:
 68             print("用户名或密码错误!")
 69             continue
 70 
 71 
 72 # 主函数:
 73 
 74 # 登录:
 75 print("购物车系统:  输入q将退出系统")
 76 login()
 77 
 78 # 输入工资
 79 salary = input_choice("输入你的工资: ")
 80 salary = int(salary)
 81 
 82 # 打印商品列表
 83 output_info()
 84 
 85 # 购买商品
 86 while True:
 87     # 输入商品序号
 88     good_choice = int(input_choice("请输入想购买的商品的序号: "))
 89     # 获取商品字典和商品价格
 90     good_dict = goods[good_choice - 1]
 91     price = good_dict['price']
 92 
 93     # 没钱了:
 94     if salary == 0:
 95         # 高亮输出花完了钱
 96         output_highlight("你的工资已经花完了!")
 97         break
 98 
 99     # 可以买的情况:
100     elif price <= salary:
101         # 获取商品名字
102         name = good_dict['name']
103         # 遍历购物车,如果购物车中已有该商品把商品数直接加一,否则就加入商品
104         for index, shopping_good in enumerate(shopping_cart):
105             # 找到商品,商品数加一
106             if shopping_good['name'] == name:
107                 shopping_good['number'] += 1
108                 break
109         else:
110             # 加入商品
111             good_dict['number'] = 1
112             shopping_cart.append(good_dict)
113         # 在薪水中减去花的钱
114         salary -= price
115         # 高亮显示余额及加入购物车
116         output_highlight("%s已加入购物车" % name)
117         output_highlight("你还有%d元钱" % salary)
118         continue
119     # 不可以买的情况:
120     else:
121         # 高亮输出余额不足
122         output_highlight("余额不足,请换一件商品或退出系统!")
123         continue
124 
125 # 退出时,打印已购买商品和余额
126 output_shopping_salary()

升级需求实现:

(1)加上第一个升级需求,每一次的余额会保存到下一次

  1 # 用户信息
  2 user_info = {
  3     'wyb': '666',
  4 }
  5 
  6 # 打开文件读取第一行数据, 即为用户工资
  7 f = open("money.txt", "r", encoding="utf-8")
  8 salary = int(f.readline())
  9 f.close()
 10 
 11 # 商品列表
 12 goods = [
 13     {"name": "电脑", "price": 1999},
 14     {"name": "鼠标", "price": 10},
 15     {"name": "游艇", "price": 20},
 16     {"name": "美女", "price": 998},
 17 ]
 18 
 19 # 购物车列表 -> [{"name": "电脑", "price": 1999, "number": 1}...]
 20 # 升级需求 -> 存入文件中
 21 shopping_cart = []
 22 
 23 
 24 # 高亮输出字符串
 25 def output_highlight(s):
 26     print('33[1;31;40m%s33[0m' % s)
 27 
 28 
 29 # 打印商品列表
 30 def output_info():
 31     print("info".center(36, '*'))
 32     print("		%s	%s" % ("name", "price"))
 33     for index, item in enumerate(goods):
 34         print("	%d.  %s		%d " % (index+1, item['name'], item['price']))
 35     print("end".center(36, '*'))
 36 
 37 
 38 # 退出时打印已购买商品和余额
 39 def output_shopping_salary():
 40     # 打印余额
 41     output_highlight('		你还剩下: %d元33[0m' % salary)
 42     # 将余额存入文件中
 43     f1 = open("money.txt", "w", encoding="utf-8")
 44     f1.write(str(salary))
 45     f1.close()
 46     # 打印已购买商品
 47     print("shopping_cart".center(36, '-'))
 48     print("		%s	%s	%s" % ("name", "price", "number"))
 49     for index, item in enumerate(shopping_cart):
 50         print("%5d.%4s%8d%8d " % (index + 1, item['name'], item['price'], item['number']))
 51     print("end".center(36, '-'))
 52 
 53 
 54 # 选择函数,专门负责输入处理
 55 def input_choice(string):
 56     choices = input(string).strip()
 57     if choices == 'q':
 58         # 退出时,打印已购买商品和余额
 59         output_shopping_salary()
 60         exit()
 61 
 62     return choices
 63 
 64 
 65 # 登录验证程序:
 66 def login():
 67     count = 0
 68     while True:
 69         count += 1
 70         username = input_choice("username: ")
 71         password = input_choice("password: ")
 72         # 当输入3次并且第3次也错误的情况下用户不能再登录
 73         if count >= 3 and user_info.get(username, None) != password:
 74             print("你已经错了太多次了!不能再试了!")
 75             exit()
 76         if user_info.get(username, None) == password:
 77             print("登录成功!")
 78             return 0
 79         else:
 80             print("用户名或密码错误!")
 81             continue
 82 
 83 
 84 # 主函数:
 85 
 86 # 登录:
 87 print("购物车系统:  在任意地方输入q将退出系统")
 88 login()
 89 
 90 # 输入工资
 91 if salary == 0:
 92     salary = input_choice("输入你的工资: ")
 93     salary = int(salary)
 94 
 95 # 打印商品列表及工资
 96 output_info()
 97 print("你有%d元钱" % salary)
 98 
 99 # 购买商品
100 while True:
101     # 输入商品序号
102     good_choice = int(input_choice("请输入想购买的商品的序号: "))
103     # 获取商品字典和商品价格
104     good_dict = goods[good_choice - 1]
105     price = good_dict['price']
106 
107     # 没钱了:
108     if salary == 0:
109         # 高亮输出花完了钱
110         output_highlight("你的工资已经花完了!")
111         break
112 
113     # 可以买的情况:
114     elif price <= salary:
115         # 获取商品名字
116         name = good_dict['name']
117         # 遍历购物车,如果购物车中已有该商品把商品数直接加一,否则就加入商品
118         for index, shopping_good in enumerate(shopping_cart):
119             # 找到商品,商品数加一
120             if shopping_good['name'] == name:
121                 shopping_good['number'] += 1
122                 break
123         else:
124             # 加入商品
125             good_dict['number'] = 1
126             shopping_cart.append(good_dict)
127         # 在薪水中减去花的钱
128         salary -= price
129         # 高亮显示余额及加入购物车
130         output_highlight("%s已加入购物车" % name)
131         output_highlight("你还有%d元钱" % salary)
132         continue
133     # 不可以买的情况:
134     else:
135         # 高亮输出余额不足
136         output_highlight("余额不足,请换一件商品或退出系统!")
137         continue
138 
139 # 退出时,打印已购买商品和余额
140 output_shopping_salary()

(2)两个升级需求全部实现

  1 # __author__ = "wyb"
  2 # date: 2018/4/18
  3 
  4 
  5 # 用户信息
  6 user_info = {
  7     'wyb': '666',
  8 }
  9 
 10 # 打开文件读取第一行数据, 即为用户工资
 11 f = open("money.txt", "r", encoding="utf-8")
 12 salary = int(f.readline())
 13 f.close()
 14 
 15 # 商品列表
 16 goods = [
 17     {"name": "电脑", "price": 1999},
 18     {"name": "鼠标", "price": 10},
 19     {"name": "游艇", "price": 20},
 20     {"name": "美女", "price": 998},
 21 ]
 22 
 23 # 购物车列表 -> [{"name": "电脑", "price": 1999, "number": 1}...]
 24 # 升级需求 -> 存入文件中
 25 shopping_cart = []
 26 
 27 
 28 # 高亮输出字符串
 29 def output_highlight(s):
 30     print('33[1;31;40m%s33[0m' % s)
 31 
 32 
 33 # 打印商品列表
 34 def output_info():
 35     print("商品列表".center(36, '*'))
 36     print("		%s	%s" % ("name", "price"))
 37     for index, item in enumerate(goods):
 38         print("	%d.  %s		%d " % (index+1, item['name'], item['price']))
 39     print("end".center(36, '*'))
 40 
 41 
 42 # 退出之前将购物车的数据以添加的方式写入文件中
 43 def before_exit():
 44     file = open("shopping_cart.txt", "a+", encoding="utf-8")
 45     for item in shopping_cart:
 46         file.write(str(item)+"
")
 47     file.close()
 48 
 49 
 50 # 打印购物记录
 51 def output_shopping_records():
 52     file = open("shopping_cart.txt", "r", encoding="utf-8")
 53     s = file.readlines()
 54     print("购物记录如下: ")
 55     if not s:
 56         print("无购物记录")
 57     else:
 58         print("商品 单价 数量")
 59         for item in s:
 60             item = eval(item.strip())
 61             # print(type(item))
 62             print(item['name'], str(item['price'])+"", item['number'])
 63     output_highlight("你还有%d元钱" % salary)
 64     file.close()
 65 
 66 
 67 # 退出时打印已购买商品和余额
 68 def output_shopping_salary():
 69     # 打印余额
 70     output_highlight('		你还剩下: %d元33[0m' % salary)
 71     # 将余额存入文件中
 72     f1 = open("money.txt", "w", encoding="utf-8")
 73     f1.write(str(salary))
 74     f1.close()
 75     # 打印已购买商品
 76     print("shopping_cart".center(36, '-'))
 77     print("		%s	%s	%s" % ("name", "price", "number"))
 78     for index, item in enumerate(shopping_cart):
 79         print("%5d.%4s%8d%8d " % (index + 1, item['name'], item['price'], item['number']))
 80     print("end".center(36, '-'))
 81 
 82 
 83 # 选择函数,专门负责输入处理
 84 def input_choice(string):
 85     choices = input(string).strip()
 86     if choices == 'q':
 87         # 退出之前
 88         before_exit()
 89         # 退出时,打印已购买商品和余额
 90         output_shopping_salary()
 91         exit()
 92 
 93     return choices
 94 
 95 
 96 # 登录验证程序:
 97 def login():
 98     count = 0
 99     while True:
100         count += 1
101         username = input_choice("username: ")
102         password = input_choice("password: ")
103         # 当输入3次并且第3次也错误的情况下用户不能再登录
104         if count >= 3 and user_info.get(username, None) != password:
105             print("你已经错了太多次了!不能再试了!")
106             exit()
107         if user_info.get(username, None) == password:
108             print("登录成功!")
109             return 0
110         else:
111             print("用户名或密码错误!")
112             continue
113 
114 
115 # 主函数:
116 
117 # 登录:
118 print("购物车系统:  在任意地方输入q将退出系统")
119 c = input("输入c查询之前的购物记录, 输入q退出系统,输入其他继续访问: ")
120 if c == 'c':
121     output_shopping_records()
122     exit()
123 elif c == 'q':
124     exit()
125 else:
126     login()
127 
128 # 输入工资
129 if salary == 0:
130     salary = input_choice("输入你的工资: ")
131     salary = int(salary)
132 
133 # 打印商品列表及工资
134 output_info()
135 output_highlight("你还有%d元钱" % salary)
136 
137 # 购买商品
138 while True:
139     # 输入商品序号
140     good_choice = int(input_choice("请输入想购买的商品的序号: "))
141     # 获取商品字典和商品价格
142     good_dict = goods[good_choice - 1]
143     price = good_dict['price']
144 
145     # 没钱了:
146     if salary == 0:
147         # 高亮输出花完了钱
148         output_highlight("你的工资已经花完了!")
149         break
150 
151     # 可以买的情况:
152     elif price <= salary:
153         # 获取商品名字
154         name = good_dict['name']
155         # 遍历购物车,如果购物车中已有该商品把商品数直接加一,否则就加入商品
156         for index, shopping_good in enumerate(shopping_cart):
157             # 找到商品,商品数加一
158             if shopping_good['name'] == name:
159                 shopping_good['number'] += 1
160                 break
161         else:
162             # 加入商品
163             good_dict['number'] = 1
164             shopping_cart.append(good_dict)
165         # 在薪水中减去花的钱
166         salary -= price
167         # 高亮显示余额及加入购物车
168         output_highlight("%s已加入购物车" % name)
169         output_highlight("你还有%d元钱" % salary)
170         continue
171     # 不可以买的情况:
172     else:
173         # 高亮输出余额不足
174         output_highlight("余额不足,请换一件商品或退出系统!")
175         continue
176 
177 # 退出之前
178 before_exit()
179 
180 # 退出时,打印已购买商品和余额
181 output_shopping_salary()
原文地址:https://www.cnblogs.com/wyb666/p/8734964.html