python购物车程序
数据结构: goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, ...... ] 基本需求: 1. 启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 2. 允许用户根据商品编号购买商品 3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4. 可随时退出,退出时,打印已购买商品和余额 5. 在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示 升级需求: 1. 用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买 2. 允许查询之前的消费记录
代码一
#!/usr/bin/env python # coding: utf-8 import json, sys, os def user_login(): name_list = ["zhangsan","lisi","wangwu"] # 用户名列表 passwd_list = ["zhangsan666","lisi666","wangwu666"] # 用户的密码列表 count = [0, 0, 0] # 用户登录密码错误的次数计数 while True: name_index = 999999 # 定义一个不存在的用户的下标 name = input("请输入你的姓名:").strip() passwd = input("请输入你的密码:").strip() with open("lockedname.txt","r+", encoding="utf-8") as f: locked_name = "".join(f.readlines()).splitlines() if name in locked_name: print("用户已经被锁定,请联系管理员") continue for i in range(len(name_list)): if name == name_list[i]: name_index = name_list.index(name_list[i]) if name_index == 999999: print("用户名不存在,请重新输入") continue if name == name_list[name_index] and passwd == passwd_list[name_index]: # 判断用户名密码 print("欢迎 %s 同学"%(name_list[name_index])) return(0, name) else: count[name_index] += 1 # 同一个用户名输错密码加一 print("密码错误") if count[name_index] == 3 : print("3次密码错误,用户账号已被锁定") with open("lockedname.txt","a+", encoding="utf-8") as f: f.writelines(name_list[name_index]+"\n") break result = user_login() # 调用用户登录函数 if result[0] != 0: # 验证是否登录成功 sys.exit() goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998} ] with open("expenses_record.txt", "r", encoding="utf-8") as f: if os.path.getsize("expenses_record.txt") == 0: # 判断是否有登录过 expenses_record = {} record = [] goods_list = [] salary = int(input("请输入您的工资:").strip()) else: expenses_record = json.load(f) try: record = expenses_record[result[1]] goods_list = record[1] bought_list = " ".join(goods_list) print("账户余额:",record[0], "已购买物品:", bought_list) # 打印记录的余额,和记录的已买物品 salary = record[0] except KeyError: record = [] goods_list = [] salary = int(input("请输入您的工资:").strip()) while True: for i, good in enumerate(goods): # 生成对应序号 print(i, good["name"], good["price"]) choice = input("请输入您要购买的商品编号或q退出:").strip() if choice.lower() == "q": your_good = "" for good in goods_list: your_good += good +" " print("您已购买的商品为:", your_good) print("您的余额为%s元:"% (salary)) record = [salary, goods_list] user = result[1] expenses_record[user] = record with open("expenses_record.txt", "w", encoding="utf-8") as f: f.write(json.dumps(expenses_record)) break choice = int(choice) if salary < goods[choice]["price"]: need_money = goods[choice]["price"] - salary print("您的余额不足,还差%s元"% ( need_money )) else: salary = salary - goods[choice]["price"] goods_list.append(goods[choice]["name"]) print("\033[31;1m您已购买:%s\033[0m"%(goods[choice]["name"]), "\033[31;1m您的余额为:%s元\033[0m"%(salary))
代码二(修改版)
#!/usr/bin/env python # coding: utf-8 import json, sys, os def user_login(): user = { "zhangsan": ["zhangsan666", 3, False], "lisi": ["lisi666", 0, True], "wangwu": ["wangwu666", 0, True] } # 用户名:[密码,密码输错次数,False锁定用户] while True: name = input("请输入你的姓名:").strip() try: with open("lockedname.txt", "r+", encoding="utf-8") as f: user = json.load(f) # 若是有lockedname.txt文件,则user重新赋值 except Exception as err: pass if name not in user: print("用户名不存在,请重新输入") continue elif user[name][2] == False: print("用户已经被锁定,请联系管理员") continue elif name in user: passwd = input("请输入你的密码:").strip() if passwd == user[name][0]: # 判断用户名密码 print("欢迎 %s 同学" % (name)) user[name][1] = 0 with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f) break else: user[name][1] += 1 # 同一个用户名输错密码加一 print("密码错误") if user[name][1] >= 3: print("用户账号已被锁定") user[name][2] = False with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f) result = user_login() # 调用用户登录函数 if result[0] != 0: # 验证是否登录成功 sys.exit() goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998} ] with open("expenses_record.txt", "r", encoding="utf-8") as f: if os.path.getsize("expenses_record.txt") == 0: # 判断是否有登录过 expenses_record = {} record = [] goods_list = [] salary = int(input("请输入您的工资:").strip()) else: expenses_record = json.load(f) try: record = expenses_record[result[1]] goods_list = record[1] bought_list = " ".join(goods_list) print("账户余额:",record[0], "已购买物品:", bought_list) # 打印记录的余额,和记录的已买物品 salary = record[0] except KeyError: record = [] goods_list = [] salary = int(input("请输入您的工资:").strip()) while True: for i, good in enumerate(goods): # 生成对应序号 print(i, good["name"], good["price"]) choice = input("请输入您要购买的商品编号或q退出:").strip() if choice.lower() == "q": your_good = "" for good in goods_list: your_good += good +" " print("您已购买的商品为:", your_good) print("您的余额为%s元:"% (salary)) record = [salary, goods_list] user = result[1] expenses_record[user] = record with open("expenses_record.txt", "w", encoding="utf-8") as f: f.write(json.dumps(expenses_record)) break choice = int(choice) if salary < goods[choice]["price"]: need_money = goods[choice]["price"] - salary print("您的余额不足,还差%s元"% ( need_money )) else: salary = salary - goods[choice]["price"] goods_list.append(goods[choice]["name"]) print("\033[31;1m您已购买:%s\033[0m"%(goods[choice]["name"]), "\033[31;1m您的余额为:%s元\033[0m"%(salary))
代码三(修改版)
#!/usr/bin/env python # coding=utf-8 # __author__ = "zhaohongwei" # Date: 2019/3/9 import json, sys, os def user_login(): user = { "zhangsan": ["zhangsan666", 3, False], "lisi": ["lisi666", 0, True], "wangwu": ["wangwu666", 0, True] } # 用户名:[密码,密码输错次数,False锁定用户] while True: name = input("请输入你的姓名:").strip() try: with open("lockedname.txt", "r+", encoding="utf-8") as f: user = json.load(f) # 若是有lockedname.txt文件,则user重新赋值 except Exception as err: pass if name not in user: print("用户名不存在,请重新输入") continue elif user[name][2] == False: print("用户已经被锁定,请联系管理员") continue elif name in user: passwd = input("请输入你的密码:").strip() if passwd == user[name][0]: # 判断用户名密码 print("欢迎 %s 同学" % (name)) user[name][1] = 0 with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f) return (0, name) else: user[name][1] += 1 # 同一个用户名输错密码加一 print("密码错误") if user[name][1] >= 3: print("用户账号已被锁定") user[name][2] = False with open("lockedname.txt", "w", encoding="utf-8") as f: json.dump(user, f) result = user_login() # 调用用户登录函数 print(result) if result[0] != 0: # 验证是否登录成功 sys.exit() goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998} ] with open("expenses_record.txt", "r", encoding="utf-8") as f: if os.path.getsize("expenses_record.txt") == 0: # 判断是否有登录过 expenses_record = {} expenses_record[result[1]] = { "credit": 0, "cart_history": {}, # 购物车历史记录 商品名/单价/数量 "credit_balance": 0, # 余额 "cash": 0, "frozen": False } record = expenses_record[result[1]] goods_list = expenses_record[result[1]]["cart_history"] salary = int(input("请输入您的工资:").strip()) else: expenses_record = json.load(f) try: record = expenses_record[result[1]] goods_list = record["cart_history"] bought_list = " ".join(goods_list) print("账户余额:",record["credit_balance"], "已购买物品:", bought_list) # 打印记录的余额,和记录的已买物品 salary = record["credit_balance"] except KeyError as err: print(err) record = expenses_record[result[1]] = {} goods_list = expenses_record[result[1]]["cart_history"] = {} salary = int(input("请输入您的工资:").strip()) while True: for i, good in enumerate(goods): # 生成对应序号 print(i, good["name"], good["price"]) choice = input("请输入您要购买的商品编号或q退出:").strip() if choice.lower() == "q": your_good = "" for good in goods_list: your_good += good +" "+str(goods_list[good][1])+"个"+" " print("您已购买的商品为:%s"%(your_good)) print("您的余额为%s元:"% (salary)) record["credit"] = 0 record["cart_history"] = goods_list record["credit_balance"] = salary # 余额 record["cash"] = 0 record["frozen"] = False user = result[1] expenses_record[user] = record with open("expenses_record.txt", "w", encoding="utf-8") as f: f.write(json.dumps(expenses_record)) break choice = int(choice) if salary < goods[choice]["price"]: need_money = goods[choice]["price"] - salary print("您的余额不足,还差%s元"% ( need_money )) else: salary = salary - goods[choice]["price"] num = 1 if goods[choice]["name"] in goods_list: num = goods_list[goods[choice]["name"]][1] num += 1 goods_list[goods[choice]["name"]] = [goods[choice]["price"], num] print("\033[31;1m您已购买:%s\033[0m"%(goods[choice]["name"]), "\033[31;1m您的余额为:%s元\033[0m"%(salary))