第2章 Python基础-字符编码&数据类型 购物车&多级菜单 作业
作业
一、三级菜单
数据结构:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
menu = { '北京':{ '海淀':{ '五道口':{ 'soho':{}, '网易':{}, 'google':{} }, '中关村':{ '爱奇艺':{}, '汽车之家':{}, 'youku':{}, }, '上地':{ '百度':{}, }, }, '昌平':{ '沙河':{ '老男孩':{}, '北航':{}, }, '天通苑':{}, '回龙观':{}, }, '朝阳':{}, '东城':{}, }, '上海':{ '闵行':{ "人民广场":{ '炸鸡店':{} } }, '闸北':{ '火车站':{ '携程':{} } }, '浦东':{}, }, '山东':{}, }
需求:
- 可依次选择进入各子菜单
- 可从任意一层往回退到上一层
- 可从任意一层退出程序
所需新知识点:列表、字典
#!/usr/bin/env python # -*- coding:utf-8 -*- # 输入省份、城市、县名称 China = { '河南省': { '焦作市': ['武陟', '温县', '博爱'], '郑州市': ['新郑', '荥阳', '中牟'], '开封市': ['兰考', '尉氏', '杞县'], }, '广东省': { '广州市': ['越秀', '荔湾', '番禺'], '深圳市': ['福田', '罗湖', '龙岗'], '东莞市': ['莞城', '南城', '东城'], }, } exit_flag = False while not exit_flag: # 第1层循环 print("\33[31;1m---------------------------------\33[1m") print(" \33[31;1m欢迎您来到中国\33[1m ") print("\33[31;1m---------------------------------\33[1m") for Province in China: print(Province) print() choice_province = input("1.请输入您要前往的 省份 (输入q退出,输入b返回上级):") print() if choice_province == "q": exit_flag = True elif choice_province == "b": continue # 跳出第1层循环的剩下语句,继续进行下一次循环(选择省份) elif choice_province in China: while not exit_flag: # 第2层循环 for City in China[choice_province]: print(City) print() choice_city = input("2.请输入您要前往的 市区 (输入q退出,输入b返回上级):") print() if choice_city == "q": exit_flag = True elif choice_city == "b": break # 跳出整个第2层循环,重新进行第1层循环(选择省份) elif choice_city in China[choice_province]: while not exit_flag: # 第3层循环 for County in China[choice_province][choice_city]: print(County) print() choice_county = input("3.请输入您要前往的 县 (输入q退出,输入b返回上级):") print() if choice_county == "q": exit_flag = True elif choice_county == "b": break # 跳出整个第3层循环,重新进行第2层循环(选择市区) elif choice_county in China[choice_province][choice_city]: print("---------------------------------") print("您现在的位置是:", choice_province, choice_city, choice_county) print("---------------------------------") exit_flag = True else: print("您输入的县不存在") print() continue else: print("您输入的市区不存在") print() continue else: print("您输入的省份不存在") print() continue
#!/usr/bin/env python # -*- coding:utf-8 -*- # 输入省份、城市、县序号 China = { '河南省': { '焦作市': ['武陟', '温县', '博爱'], '郑州市': ['新郑', '荥阳', '中牟'], '开封市': ['兰考', '尉氏', '杞县'], }, '广东省': { '广州市': ['越秀', '荔湾', '番禺'], '深圳市': ['福田', '罗湖', '龙岗'], '东莞市': ['莞城', '南城', '东城'], }, } exit_flag = False while not exit_flag: # 第1层循环 province_list = [] # 定义一个省份列表 city_list = [] # 定义一个城市列表 print("\33[31;1m---------------------------------\33[1m") print(" \33[31;1m欢迎您来到中国\33[1m ") print("\33[31;1m---------------------------------\33[1m") for index,Province in enumerate(China,1): print("%s. %s" % (index,Province)) province_list.append(Province) # 添加所有省份到省份列表中 print() choice_province = input("一.请输入您要前往的省份序号 (输入q退出,输入b返回上级):") print() if choice_province == "q" or choice_province == "Q": exit_flag = True elif choice_province == "b" or choice_province == "B": continue # 跳出第1层循环的剩下语句,继续进行下一次循环(选择省份) elif choice_province.isdigit(): choice_province = int(choice_province) if choice_province >= 1 and choice_province <= len(province_list): while not exit_flag: # 第2层循环 for index,City in enumerate(China[province_list[choice_province-1]],1): print("%s. %s" % (index,City)) city_list.append(City) # 添加所有城市到城市列表中 print() choice_city = input("二.请输入您要前往的城市序号 (输入q退出,输入b返回上级):") print() if choice_city == "q" or choice_city == "Q": exit_flag = True elif choice_city == "b" or choice_city == "B": break # 跳出整个第2层循环,重新进行第1层循环(选择省份) elif choice_city.isdigit(): choice_city = int(choice_city) if choice_city >=1 and choice_city <= len(city_list): while not exit_flag: # 第3层循环 for index,County in enumerate(China[province_list[choice_province-1]][city_list[choice_city-1]],1): print("%s. %s" % (index, County)) print() choice_county = input("三.请输入您要前往的县序号 (输入q退出,输入b返回上级):") print() if choice_county == "q" or choice_county == "Q": exit_flag = True elif choice_county == "b" or choice_county == "b": break # 跳出整个第3层循环,重新进行第2层循环(选择城市) elif choice_county.isdigit(): choice_county = int(choice_county) county_list = China[province_list[choice_province - 1]][city_list[choice_city - 1]] # 县列表 if choice_county >= 1 and choice_county <= len(county_list): print("---------------------------------") print("您现在的位置是:", province_list[choice_province-1],city_list[choice_city-1],county_list[choice_county-1]) print("---------------------------------") exit_flag = True else: print("您输入的县序号不存在") print() else: print("您输入的县序号不存在") print() continue else: print("您输入的城市序号不存在") print() continue else: print("您输入的城市序号不存在") print() continue else: print("您输入的省份序号不存在") print() else: print("您输入的省份序号不存在") print() continue
最终版本:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- # 三级菜单 menu = { '北京': { '海淀': { '五道口': { 'soho': {}, '网易': {}, 'google': {} }, '中关村': { '爱奇艺': {}, '汽车之家': {}, 'youku': {}, }, '上地': { '百度': {}, }, }, '昌平': { '沙河': { '老男孩': {}, '北航': {}, }, '天通苑': {}, '回龙观': {}, }, '朝阳': {}, '东城': {}, }, '上海': { '闵行': { "人民广场": { '炸鸡店': {} } }, '闸北': { '火车站': { '携程': {} } }, '浦东': {}, }, '山东': {}, } current_layer = menu # 最高层次为menu(是一个字典) layer_list = [] # 存放每次进入的层次,用于退回上层 while True: for k in current_layer: # 遍历字典key print("\n", k) choice = input("\n\033[34;1m请输入您要前往的地址(输入q退出,输入b返回上级)>>>\033[0m").strip() if choice == 'q' or choice == 'Q': # 可从任意一层退出程序 break elif choice == 'b' or choice == 'B': # 可从任意一层往回退到上一层 if not layer_list: print("\n\033[31;1m到顶了,哥\033[0m\n") else: current_layer = layer_list.pop() elif choice not in current_layer: print("\n\033[31;1m输入有误,请重新输入\033[0m\n") else: layer_list.append(current_layer) # 在列表末尾追加当前层次(是一个字典) current_layer = current_layer[choice] # 下一个层次(也就是下一次要遍历的字典) if not current_layer: print("\n\033[31;1m到底了,哥\033[0m")
二、购物车程序
数据结构:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ...... ]
功能要求:
1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
扩展需求:
1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
2、允许查询之前的消费记录
1.0版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 goods = [ 5 {"name": "电脑", "price": 3999}, 6 {"name": "鼠标", "price": 200}, 7 {"name": "游艇", "price": 2000}, 8 {"name": "美女", "price": 998}, 9 {"name": "T恤", "price": 599}, 10 ] 11 12 shopping_carts = [] # 初始购物车为空 13 money = 0 # 初始工资为空 14 money += int(input("请输入您的工资:")) # 只能输入数字 15 exit_flag = False 16 17 while not exit_flag: 18 print("\n------------商品列表-----------\n") # 商品列表 19 for index, product in enumerate(goods, 1): 20 print("%s.%s %d" % (index, product['name'], product['price'])) 21 print("\n-------------------------------\n") 22 product_id = input("请输入您要购买的商品编号(输入q可退出):") 23 if product_id.isdigit(): 24 product_id = int(product_id) 25 if product_id >= 1 and product_id <= len(goods): 26 if money >= goods[product_id - 1]['price']: 27 money -= goods[product_id - 1]['price'] 28 shopping_carts.append(goods[product_id - 1]['name']) 29 print("\n\33[31;1m%s已加入购物车!\33[1m\n" % (goods[product_id - 1]['name'])) 30 else: 31 print("\n\33[31;1m抱歉,%s加入购物车失败!工资余额不足!\33[1m\n" % (goods[product_id - 1]['name'])) 32 # exit_flag =True 33 else: 34 print("商品标号有误,请重新输入") 35 elif product_id == "q": 36 if len(shopping_carts) > 0: 37 print("\n\33[31;1m您添加到购物车的商品如下:\33[1m\n") 38 for index, product_carts in enumerate(shopping_carts, 1): 39 print("%s. %s" % (index, product_carts)) 40 else: 41 print("\n您的购物车为空!") 42 print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money)) 43 exit_flag = True 44 else: 45 pass
1.1版本
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- goods = [ {"name": "电脑", "price": 3999}, {"name": "鼠标", "price": 200}, {"name": "游艇", "price": 2000}, {"name": "美女", "price": 998}, {"name": "T恤", "price": 599}, ] exit_flag = False shopping_carts = [] # 初始购物车为空 money = 0 # 初始工资为空 while True: salary = input("\n请输入您的工资:") # 工资只能是数字 if salary.isdigit(): money += int(salary) break else: print("\n您的工资只能是数字") continue while not exit_flag: print("\n------------商品列表-----------\n") # 商品列表 for index, product in enumerate(goods, 1): print("%s.%s %d" % (index, product['name'], product['price'])) print("\n-------------------------------\n") product_id = input("请输入您要购买的商品编号(输入q可退出):") if product_id.isdigit(): product_id = int(product_id) if product_id >= 1 and product_id <= len(goods): if money >= goods[product_id - 1]['price']: money -= goods[product_id - 1]['price'] shopping_carts.append(goods[product_id - 1]['name']) print("\n\33[31;1m%s已加入购物车!\33[1m\n" % (goods[product_id - 1]['name'])) else: print("\n\33[31;1m抱歉,%s加入购物车失败!工资余额不足!\33[1m\n" % (goods[product_id - 1]['name'])) # exit_flag =True else: print("商品标号有误,请重新输入") elif product_id == "q": if len(shopping_carts) > 0: print("\n\33[31;1m您添加到购物车的商品如下:\33[1m\n") shopping_carts_delRepeat = list(set(shopping_carts)) # 购物车列表去重 for index, product_carts in enumerate(shopping_carts_delRepeat, 1): print("%s. %s * %d" % (index, product_carts, shopping_carts.count(product_carts))) # 显示同一商品数量 else: print("\n您的购物车为空!") print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money)) exit_flag = True else: print("\n输入有误,请重新输入")
1.2版本
userinfo.txt:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
alex:456:0:400 wss:123:0:1150 jay:789:1:0
shopping_history.txt:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
wss|2018-05-20 12:10:08|电脑 wss|2018-05-20 14:10:09|电脑 wss|2018-05-21 17:11:08|电脑 jay|2018-05-22 19:13:08|电脑 alex|2018-05-23 17:15:08|鼠标 wss|2018-05-23 19:06:24|鼠标 wss|2018-05-23 19:06:57|鼠标 wss|2018-05-23 19:11:46|鼠标 wss|2018-05-23 19:14:12|鼠标 wss|2018-05-23 19:14:30|鼠标 wss|2018-05-23 19:15:17|鼠标 alex|2018-05-23 19:16:12|鼠标 alex|2018-05-23 19:16:51|鼠标
README.txt
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
user_info.txt 存储用户名、密码、锁定状态、工资余额 wss:123:1:5800 alex:456:0:55000 jay:789:0:0 用户名:密码:锁定状态(1代表锁定,0代表未锁定):工资余额 wss是输错密码次数过多,被锁定的用户。 alex是之前登陆过的用户,登陆之后可以看到工资余额,可继续购买。 jay是从未登陆过的新用户,登陆之后需要输入工资,然后才能购买。 shopping_history.txt 存储消费记录 wss|2018-05-20 12:10:08|电脑 wss|2018-05-20 14:10:09|电脑 wss|2018-05-21 17:11:08|电脑 jay|2018-05-22 19:13:08|电脑 alex|2018-05-23 17:15:08|鼠标 wss|2018-05-23 19:06:24|鼠标 wss|2018-05-23 19:06:57|鼠标 买家用户名|日期|商品名称 shoping.py 主程序 ------------------------------- 请输入用户名:alex 请输入密码:456 --------欢迎 alex 登陆商城-------- 您上次购物后的余额为:350 元! ------------商品列表------------ 1.电脑 4000 2.鼠标 200 3.游艇 20000 4.美女 1000 5.T恤 50 ------------------------------- 【商品编号】购买商品 【h】消费记录 【m】余额查询 【q】退出商城 ------------------------------- 请输入您要的操作:h ---------您的消费记录---------- 用户 alex 2018-05-23 17:15:08 购买了 鼠标 用户 alex 2018-05-23 19:16:12 购买了 鼠标 用户 alex 2018-05-23 19:16:51 购买了 鼠标 用户 alex 2018-05-23 19:16:52 购买了 鼠标 用户 alex 2018-05-23 19:18:00 购买了 T恤 用户 alex 2018-05-23 22:35:06 购买了 鼠标 用户 alex 2018-05-25 18:12:41 购买了 鼠标 用户 alex 2018-05-25 18:16:25 购买了 电脑 用户 alex 2018-05-25 18:31:56 购买了 电脑 用户 alex 2018-05-25 18:34:44 购买了 鼠标 用户 alex 2018-05-25 18:36:02 购买了 鼠标 用户 alex 2018-05-26 20:00:34 购买了 鼠标 用户 alex 2018-05-26 20:00:37 购买了 美女 用户 alex 2018-05-26 20:00:38 购买了 T恤 ------------------------------- 请输入您要的操作:m 您的工资余额为:350 元! ------------------------------- 请输入您要的操作:5 T恤已购买成功! ------------------------------- 请输入您要的操作:q 您本次没有购买东西! 您的工资余额为:350 元! -------------------------------
shopping.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import time def select_user_info(): # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f: for line in user_info_f: # 用户信息字符串 user_info_list = line.strip().split(':') # 将字符串转换为列表 # print(user_info_list) # 用户信息列表 _username = user_info_list[0].strip() # 用户名 _password = user_info_list[1].strip() # 密码 _lock = int(user_info_list[2].strip()) # 锁定状态,int类型(0代表未锁定,1代表锁定) _money = user_info_list[3].strip() # 余额 user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money} # 将列表转换为字典 # print(user_info_dict) # 用户信息字典 def update_user_info(): # 修改用户信息后,更新user_info.txt文件内容 with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp: for user in user_info_dict: # 将字典转换为列表 user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']), str(user_info_dict[user]['money'])] # print(user_info_list_new) # 更新后的用户信息列表 user_info_str = ":".join(user_info_list_new) # 将列表转换为字符串 # print(user_str) # 更新后的用户信息字符串 user_info_f_temp.write(user_info_str + "\n") os.replace(user_info_f_temp_name, user_info_f_name) def product_list(): # 商品列表 print("\n------------商品列表------------\n") # 商品列表 for index, product in enumerate(goods, 1): print("%s.%s %d" % (index, product['name'], product['price'])) print("\n-------------------------------") def select_shopping_history(): # 读取消费记录 with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f: print("\n------------消费记录-----------\n") for line in shopping_history_f: shopping_history_list = line.strip().split('|') # print(shopping_history_list) _username = shopping_history_list[0].strip() _time = shopping_history_list[1].strip() _product = shopping_history_list[2].strip() if username in shopping_history_list: print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product)) else: pass print("\n-------------------------------") def update_shopping_history(): # 更新消费记录 now_time = time.strftime('%Y-%m-%d %H:%M:%S') with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f: shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name'])) # 商品信息 goods = [ {"name": "电脑", "price": 4000}, {"name": "鼠标", "price": 200}, {"name": "游艇", "price": 20000}, {"name": "美女", "price": 1000}, {"name": "T恤", "price": 50}, ] # 菜单栏 choice_info = """ 【商品编号】购买商品 【h】消费记录 【m】余额查询 【q】退出商城 ------------------------------- """ shopping_carts = [] # 初始购物车为空 user_info_dict = {} # 初始化用户信息字典为空 user_info_f_name = "user_info.txt" # 用户信息文件名 user_info_f_temp_name = "user_info.txt.temp" # 用户信息临时文件名 shopping_history_f_name = "shopping_history.txt" # 消费记录 exit_flag = False count = 0 # 主程序开始 select_user_info() # 读取用户信息文件,组成user_info_dict字典 while count < 3 and not exit_flag: username = input('\n请输入用户名:') if username not in user_info_dict: count += 1 print("\n用户名错误") elif user_info_dict[username]['lock'] > 0: print("\n用户已被锁定,请联系管理员解锁后重新尝试") break else: while count < 3 and not exit_flag: password = input('\n请输入密码:') if password == user_info_dict[username]['password']: print("\n--------欢迎%s登陆本商城--------" % (username)) if int(user_info_dict[username]['money']) == 0: # money = 0表示是首次登陆的用户 while True: money = input("\n请输入您的工资:") # 工资只能是数字 if money.isdigit(): money = int(money) # print(money) break else: print("\n您的工资只能是数字") continue else: money = int(user_info_dict[username]['money']) print("\n\33[31;1m您上次购物后的余额为:%s 元!\33[1m\n" % (money)) while not exit_flag: product_list() # 打印商品列表 print(choice_info) # 选择信息 product_id = input("请输入您要的操作:") if product_id.isdigit(): product_id = int(product_id) if product_id >= 1 and product_id <= len(goods): if money >= goods[product_id - 1]['price']: money -= goods[product_id - 1]['price'] shopping_carts.append(goods[product_id - 1]['name']) print("\n\33[31;1m%s已购买成功!\33[1m\n" % (goods[product_id - 1]['name'])) update_shopping_history() # 写入消费记录文件 user_info_dict[username]['money'] = money update_user_info() # 更新工资余额到文件 else: print( "\n\33[31;1m抱歉,%s购买失败!工资余额不足!\33[1m\n" % (goods[product_id - 1]['name'])) else: print("商品标号有误,请重新输入") elif product_id == "q": if len(shopping_carts) > 0: print("\n\33[31;1m您本次购买的商品及商品数量如下:\33[1m\n") shopping_carts_delRepeat = list(set(shopping_carts)) # 购物车列表去重 for index, product_carts in enumerate(shopping_carts_delRepeat, 1): print("%s. %s * %d" % ( index, product_carts, shopping_carts.count(product_carts))) # 显示同一商品数量 else: print("\n您本次没有购买东西!") print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money)) # user_info_dict[username]['money'] = money # update_user_info() # 更新工资余额到文件 exit_flag = True elif product_id == "h": select_shopping_history() choice_continue = input("\n回到菜单栏(直接按回车):") if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n操作失误,强制退出!") exit_flag = True elif product_id == "m": print("\n\33[31;1m您的工资余额为:%s 元!\33[1m\n" % (money)) # user_info_dict[username]['money'] = money # update_user_info() # 更新工资余额到文件 choice_continue = input("\n回到菜单栏(直接按回车):") if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n操作失误,强制退出!") exit_flag = True else: print("\n输入有误,请重新输入") else: count += 1 print('\n密码错误') continue if count >= 3: # 尝试次数大于等于3时锁定用户 if username == "": print("\n您输入的错误次数过多,且用户为空") elif username not in user_info_dict: print("\n您输入的错误次数过多,且用户 %s 不存在" % username) else: user_info_dict[username]['lock'] += 1 # 修改用户字典(锁定状态设为1) # print(user_info_dict) # 更新后的用户信息字典 update_user_info() # 更新user_info.txt文件内容 print("\n您输入的错误次数过多,%s 已经被锁定" % username)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import time def select_user_info(): # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f: for line in user_info_f: # 用户信息字符串 user_info_list = line.strip().split(':') # 将字符串转换为列表 # print(user_info_list) # 用户信息列表 _username = user_info_list[0].strip() # 用户名 _password = user_info_list[1].strip() # 密码 _lock = int(user_info_list[2].strip()) # 锁定状态,int类型(0代表未锁定,1代表锁定) _money = user_info_list[3].strip() # 余额 user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money} # 将列表转换为字典 # print(user_info_dict) # 用户信息字典 def update_user_info(): # 修改用户信息后,更新user_info.txt文件内容 with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp: for user in user_info_dict: # 将字典转换为列表 user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']), str(user_info_dict[user]['money'])] # print(user_info_list_new) # 更新后的用户信息列表 user_info_str = ":".join(user_info_list_new) # 将列表转换为字符串 # print(user_str) # 更新后的用户信息字符串 user_info_f_temp.write(user_info_str + "\n") os.replace(user_info_f_temp_name, user_info_f_name) def product_list(): # 商品列表 print("\n------------商品列表------------\n") # 商品列表 for index, product in enumerate(goods, 1): print("%s.%s %d" % (index, product['name'], product['price'])) print("\n-------------------------------") def select_shopping_history(): # 读取消费记录 with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f: print("\n---------您的消费记录----------\n") for line in shopping_history_f: shopping_history_list = line.strip().split('|') # print(shopping_history_list) _username = shopping_history_list[0].strip() _time = shopping_history_list[1].strip() _product = shopping_history_list[2].strip() if username in shopping_history_list: print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product)) else: pass print("\n-------------------------------") def update_shopping_history(): # 更新消费记录 now_time = time.strftime('%Y-%m-%d %H:%M:%S') with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f: shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name'])) # 商品信息 goods = [ {"name": "电脑", "price": 4000}, {"name": "鼠标", "price": 200}, {"name": "游艇", "price": 20000}, {"name": "美女", "price": 1000}, {"name": "T恤", "price": 50}, ] # 菜单栏 choice_info = """ 【商品编号】购买商品 【h】消费记录 【m】余额查询 【q】退出商城 ------------------------------- """ shopping_carts = [] # 初始购物车为空 user_info_dict = {} # 初始化用户信息字典为空 user_info_f_name = "user_info.txt" # 用户信息文件名 user_info_f_temp_name = "user_info.txt.temp" # 用户信息临时文件名 shopping_history_f_name = "shopping_history.txt" # 消费记录 exit_flag = False count = 0 # 主程序开始 select_user_info() # 读取用户信息文件,组成user_info_dict字典 while count < 3 and not exit_flag: username = input('\n请输入用户名:') if username not in user_info_dict: count += 1 print("\n用户名错误") elif user_info_dict[username]['lock'] > 0: print("\n用户已被锁定,请联系管理员解锁后重新尝试") break else: while count < 3 and not exit_flag: password = input('\n请输入密码:') if password == user_info_dict[username]['password']: print("\n--------欢迎%s登陆本商城--------" % (username)) if int(user_info_dict[username]['money']) == 0: # money = 0表示是首次登陆的用户 while True: money = input("\n请输入您的工资:") # 工资只能是数字 if money.isdigit(): money = int(money) # print(money) break else: print("\n您的工资只能是数字") continue else: money = int(user_info_dict[username]['money']) print("\n\033[31;1m您上次购物后的余额为:%s 元!\033[0m\n" % (money)) while not exit_flag: product_list() # 打印商品列表 print(choice_info) # 选择信息 product_id = input("请输入您要的操作:") if product_id.isdigit(): product_id = int(product_id) if product_id >= 1 and product_id <= len(goods): if money >= goods[product_id - 1]['price']: money -= goods[product_id - 1]['price'] shopping_carts.append(goods[product_id - 1]['name']) print("\n\033[31;1m%s已购买成功!\033[0m\n" % (goods[product_id - 1]['name'])) update_shopping_history() # 写入消费记录文件 user_info_dict[username]['money'] = money update_user_info() # 更新工资余额到文件 else: print("\n\033[31;1m抱歉,%s购买失败!工资余额不足!\033[0m" % (goods[product_id - 1]['name'])) else: print("商品标号有误,请重新输入") elif product_id == "q": if len(shopping_carts) > 0: print("\n\033[31;1m您本次购买的商品及商品数量如下:\033[0m\n") shopping_carts_delRepeat = list(set(shopping_carts)) # 购物车列表去重 for index, product_carts in enumerate(shopping_carts_delRepeat, 1): print("%s. %s * %d" % ( index, product_carts, shopping_carts.count(product_carts))) # 显示同一商品数量 else: print("\n您本次没有购买东西!") print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) # user_info_dict[username]['money'] = money # update_user_info() # 更新工资余额到文件 exit_flag = True elif product_id == "h": select_shopping_history() choice_continue = input("\n回到菜单栏(直接按回车):") if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n操作失误,强制退出!") exit_flag = True elif product_id == "m": print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) # user_info_dict[username]['money'] = money # update_user_info() # 更新工资余额到文件 choice_continue = input("\n回到菜单栏(直接按回车):") if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n操作失误,强制退出!") exit_flag = True else: print("\n输入有误,请重新输入") else: count += 1 print('\n密码错误') continue if count >= 3: # 尝试次数大于等于3时锁定用户 if username == "": print("\n您输入的错误次数过多,且用户为空") elif username not in user_info_dict: print("\n您输入的错误次数过多,且用户 %s 不存在" % username) else: user_info_dict[username]['lock'] += 1 # 修改用户字典(锁定状态设为1) # print(user_info_dict) # 更新后的用户信息字典 update_user_info() # 更新user_info.txt文件内容 print("\n您输入的错误次数过多,%s 已经被锁定" % username)
1.3版本:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import time def select_user_info(): # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f: for line in user_info_f: # 用户信息字符串 user_info_list = line.strip().split(':') # 将字符串转换为列表 # print(user_info_list) # 用户信息列表 _username = user_info_list[0].strip() # 用户名 _password = user_info_list[1].strip() # 密码 _lock = int(user_info_list[2].strip()) # 锁定状态,int类型(0代表未锁定,1代表锁定) _money = user_info_list[3].strip() # 余额 user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money} # 将列表转换为字典 # print(user_info_dict) # 用户信息字典 def update_user_info(): # 修改用户信息后,更新user_info.txt文件内容 with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp: for user in user_info_dict: # 将字典转换为列表 user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']), str(user_info_dict[user]['money'])] # print(user_info_list_new) # 更新后的用户信息列表 user_info_str = ":".join(user_info_list_new) # 将列表转换为字符串 # print(user_str) # 更新后的用户信息字符串 user_info_f_temp.write(user_info_str + "\n") os.replace(user_info_f_temp_name, user_info_f_name) def product_list(): # 商品列表 print("\n------------商品列表------------\n") # 商品列表 for index, product in enumerate(goods, 1): print("%s.%s %d" % (index, product['name'], product['price'])) print("\n-------------------------------") def select_shopping_history(): # 读取消费记录 with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f: print("\n---------您的消费记录----------\n") for line in shopping_history_f: shopping_history_list = line.strip().split('|') # print(shopping_history_list) _username = shopping_history_list[0].strip() _time = shopping_history_list[1].strip() _product = shopping_history_list[2].strip() if username in shopping_history_list: print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product)) else: pass print("\n-------------------------------") def update_shopping_history(): # 更新消费记录 now_time = time.strftime('%Y-%m-%d %H:%M:%S') with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f: shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name'])) # 商品信息 goods = [ {"name": "电脑", "price": 4000}, {"name": "鼠标", "price": 200}, {"name": "游艇", "price": 20000}, {"name": "美女", "price": 1000}, {"name": "T恤", "price": 50}, ] # 菜单栏 choice_info = """ 【商品编号】购买商品 【h】消费记录 【m】余额查询 【q】退出商城 ------------------------------- """ shopping_carts = [] # 初始购物车为空 user_info_dict = {} # 初始化用户信息字典为空 user_info_f_name = "user_info.txt" # 用户信息文件名 user_info_f_temp_name = "user_info.txt.temp" # 用户信息临时文件名 shopping_history_f_name = "shopping_history.txt" # 消费记录 count = 0 # 主程序开始 select_user_info() # 读取用户信息文件,组成user_info_dict字典 while count < 3: username = input('\n\033[34;1m请输入用户名:\033[0m').strip() if username not in user_info_dict: count += 1 print("\n\033[31;1m用户名错误\033[0m") elif user_info_dict[username]['lock'] > 0: print("\n\033[31;1m%s 已被锁定,请联系管理员解锁后重新尝试\033[0m" % (username)) exit() else: while count < 3: password = input('\n\033[34;1m请输入密码:\033[0m').strip() if password == user_info_dict[username]['password']: print("\n--------欢迎 %s 登陆商城--------" % (username)) if int(user_info_dict[username]['money']) == 0: # money = 0表示是首次登陆的用户 while True: money = input("\n\033[34;1m请输入您的工资:\033[0m") # 工资只能是数字 if money.isdigit(): money = int(money) # print(money) break else: print("\n\033[31;1m您的工资只能是数字\033[0m") continue else: money = int(user_info_dict[username]['money']) print("\n\033[31;1m您上次购物后的余额为:%s 元!\033[0m\n" % (money)) while True: product_list() # 打印商品列表 print(choice_info) # 选择信息 product_id = input("\033[34;1m请输入您要的操作:\033[0m").strip() if product_id.isdigit(): product_id = int(product_id) if product_id >= 1 and product_id <= len(goods): if money >= goods[product_id - 1]['price']: money -= goods[product_id - 1]['price'] shopping_carts.append(goods[product_id - 1]['name']) print("\n\033[31;1m%s已购买成功!\033[0m\n" % (goods[product_id - 1]['name'])) update_shopping_history() # 写入消费记录文件 user_info_dict[username]['money'] = money update_user_info() # 更新工资余额到文件 else: print("\n\033[31;1m抱歉,%s购买失败!工资余额不足!\033[0m" % (goods[product_id - 1]['name'])) else: print("\033[31;1m商品标号有误,请重新输入\033[0m") elif product_id == "q": if len(shopping_carts) > 0: print("\n\033[31;1m您本次购买的商品及商品数量如下:\033[0m\n") shopping_carts_delRepeat = list(set(shopping_carts)) # 购物车列表去重 for index, product_carts in enumerate(shopping_carts_delRepeat, 1): print("%s. %s * %d" % ( index, product_carts, shopping_carts.count(product_carts))) # 显示同一商品数量 else: print("\n\033[31;1m您本次没有购买东西!\033[0m") print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) exit() elif product_id == "h": select_shopping_history() choice_continue = input("\n\033[34;1m回到菜单栏(直接按回车):\033[0m").strip() if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n\033[31;1m操作失误,强制退出!\033[0m") exit() elif product_id == "m": print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) choice_continue = input("\n\033[34;1m回到菜单栏(直接按回车):\033[0m").strip() if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n\033[31;1m操作失误,强制退出!\033[0m") exit() else: print("\n\033[31;1m输入有误,请重新输入\033[0m") else: count += 1 print('\n\033[31;1m密码错误\033[0m') continue if count >= 3: # 尝试次数大于等于3时锁定用户 if not username: print("\n\033[31;1m您输入的错误次数过多,且用户为空\033[0m") elif username not in user_info_dict: print("\n\033[31;1m您输入的错误次数过多,且用户 %s 不存在\033[0m" % username) else: user_info_dict[username]['lock'] += 1 # 修改用户字典(锁定状态设为1) # print(user_info_dict) # 更新后的用户信息字典 update_user_info() # 更新user_info.txt文件内容 print("\n\033[31;1m您输入的错误次数过多,%s 已经被锁定\033[0m" % username)
最终版本:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding:utf-8 -*- """ @Version: V1.0 @Author: wushuaishuai @License: Apache Licence @Contact: 434631143@qq.com @Site: http://www.cnblogs.com/wushuaishuai/ @Software: PyCharm @File: shopping.py @Time: 2018/05/26 20:39 ┏┓ ┏┓ ┏┛┻━━━┛┻┓ ┃ ☃ ┃ ┃ ┳┛ ┗┳ ┃ ┃ ┻ ┃ ┗━┓ ┏━┛ ┃ ┗━━━┓ ┃ 神兽保佑 ┣┓ ┃ 永无BUG! ┏┛ ┗┓┓┏━┳┓┏┛ ┃┫┫ ┃┫┫ ┗┻┛ ┗┻┛ """ import os import time def select_user_info(): # 读取用户信息文件,取出用户名、密码、锁定状态、余额组成一个用户信息字典user_info_dict with open(user_info_f_name, 'r', encoding='utf-8') as user_info_f: for line in user_info_f: # 用户信息字符串 user_info_list = line.strip().split(':') # 将字符串转换为列表 # print(user_info_list) # 用户信息列表 _username = user_info_list[0].strip() # 用户名 _password = user_info_list[1].strip() # 密码 _lock = int(user_info_list[2].strip()) # 锁定状态,int类型(0代表未锁定,1代表锁定) _money = user_info_list[3].strip() # 余额 user_info_dict[_username] = {'password': _password, 'lock': _lock, 'money': _money} # 将列表转换为字典 # print(user_info_dict) # 用户信息字典 def update_user_info(): # 修改用户信息后,更新user_info.txt文件内容 with open(user_info_f_temp_name, "w", encoding="utf-8") as user_info_f_temp: for user in user_info_dict: # 将字典转换为列表 user_info_list_new = [user, str(user_info_dict[user]['password']), str(user_info_dict[user]['lock']), str(user_info_dict[user]['money'])] # print(user_info_list_new) # 更新后的用户信息列表 user_info_str = ":".join(user_info_list_new) # 将列表转换为字符串 # print(user_str) # 更新后的用户信息字符串 user_info_f_temp.write(user_info_str + "\n") os.replace(user_info_f_temp_name, user_info_f_name) def product_list(): # 商品列表 print("\n------------商品列表------------\n") # 商品列表 for index, product in enumerate(goods, 1): print("%s.%s %d" % (index, product['name'], product['price'])) print("\n-------------------------------") def select_shopping_history(): # 读取消费记录 with open(shopping_history_f_name, "r", encoding="utf-8") as shopping_history_f: print("\n---------您的消费记录----------\n") for line in shopping_history_f: shopping_history_list = line.strip().split('|') # print(shopping_history_list) _username = shopping_history_list[0].strip() _time = shopping_history_list[1].strip() _product = shopping_history_list[2].strip() if username in shopping_history_list: print("用户 {0} {1} 购买了 {2}".format(_username, _time, _product)) else: pass print("\n-------------------------------") def update_shopping_history(): # 更新消费记录 now_time = time.strftime('%Y-%m-%d %H:%M:%S') with open(shopping_history_f_name, "a", encoding="utf-8") as shopping_history_f: shopping_history_f.write("\n%s|%s|%s" % (username, now_time, goods[product_id - 1]['name'])) # 商品信息 goods = [ {"name": "电脑", "price": 4000}, {"name": "鼠标", "price": 200}, {"name": "游艇", "price": 20000}, {"name": "美女", "price": 1000}, {"name": "T恤", "price": 50}, ] # 菜单栏 choice_info = """ 【商品编号】购买商品 【h】消费记录 【m】余额查询 【q】退出商城 ------------------------------- """ shopping_carts = [] # 初始购物车为空 user_info_dict = {} # 初始化用户信息字典为空 user_info_f_name = "user_info.txt" # 用户信息文件名 user_info_f_temp_name = "user_info.txt.temp" # 用户信息临时文件名 shopping_history_f_name = "shopping_history.txt" # 消费记录 count = 0 # 主程序开始 select_user_info() # 读取用户信息文件,组成user_info_dict字典 while count < 3: username = input('\n\033[34;1m请输入用户名:\033[0m').strip() if username not in user_info_dict: count += 1 print("\n\033[31;1m用户名错误\033[0m") elif user_info_dict[username]['lock'] > 0: print("\n\033[31;1m%s 已被锁定,请联系管理员解锁后重新尝试\033[0m" % (username)) exit() else: while count < 3: password = input('\n\033[34;1m请输入密码:\033[0m').strip() if password == user_info_dict[username]['password']: print("\n--------欢迎 %s 登陆商城--------" % (username)) if int(user_info_dict[username]['money']) == 0: # money = 0表示是首次登陆的用户 while True: money = input("\n\033[34;1m请输入您的工资:\033[0m") # 工资只能是数字 if money.isdigit(): money = int(money) user_info_dict[username]['money'] = money update_user_info() # 更新工资余额到文件 # print(money) break else: print("\n\033[31;1m您的工资只能是数字!\033[0m") continue else: money = int(user_info_dict[username]['money']) print("\n\033[31;1m您上次购物后的余额为:%s 元!\033[0m\n" % (money)) while True: product_list() # 打印商品列表 print(choice_info) # 选择信息 product_id = input("\033[34;1m请输入您要的操作:\033[0m").strip() if product_id.isdigit(): product_id = int(product_id) if product_id >= 1 and product_id <= len(goods): if money >= goods[product_id - 1]['price']: money -= goods[product_id - 1]['price'] shopping_carts.append(goods[product_id - 1]['name']) print("\n\033[31;1m%s已购买成功!\033[0m\n" % (goods[product_id - 1]['name'])) update_shopping_history() # 写入消费记录文件 user_info_dict[username]['money'] = money update_user_info() # 更新工资余额到文件 else: print("\n\033[31;1m抱歉,%s购买失败!工资余额不足!\033[0m" % (goods[product_id - 1]['name'])) else: print("\n\033[31;1m商品编号有误,请重新输入!\033[0m") elif product_id == "q": if len(shopping_carts) > 0: print("\n\033[31;1m您本次购买的商品及商品数量如下:\033[0m\n") shopping_carts_delRepeat = list(set(shopping_carts)) # 购物车列表去重 for index, product_carts in enumerate(shopping_carts_delRepeat, 1): print("%s. %s * %d" % ( index, product_carts, shopping_carts.count(product_carts))) # 显示同一商品数量 else: print("\n\033[31;1m您本次没有购买东西!\033[0m") print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) exit() elif product_id == "h": select_shopping_history() choice_continue = input("\n\033[34;1m回到菜单栏(直接按回车):\033[0m").strip() if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n\033[31;1m操作失误,强制退出!\033[0m") exit() elif product_id == "m": print("\n\033[31;1m您的工资余额为:%s 元!\033[0m\n" % (money)) choice_continue = input("\n\033[34;1m回到菜单栏(直接按回车):\033[0m").strip() if choice_continue == 'y' or choice_continue == "Y" or choice_continue == "": continue else: print("\n\033[31;1m操作失误,强制退出!\033[0m") exit() else: print("\n\033[31;1m输入有误,请重新输入!\033[0m") else: count += 1 print('\n\033[31;1m密码错误\033[0m') continue if count >= 3: # 尝试次数大于等于3时锁定用户 if not username: print("\n\033[31;1m您输入的错误次数过多,且用户为空!\033[0m") elif username not in user_info_dict: print("\n\033[31;1m您输入的错误次数过多,且用户 %s 不存在!\033[0m" % username) else: user_info_dict[username]['lock'] += 1 # 修改用户字典(锁定状态设为1) # print(user_info_dict) # 更新后的用户信息字典 update_user_info() # 更新user_info.txt文件内容 print("\n\033[31;1m您输入的错误次数过多,%s 已经被锁定!\033[0m" % username)