购物车功能
import os
import json
# 获取执行文件所在路径
current_path = os.path.dirname(__file__)
# 拼接db文件夹的路径
data_path = os.path.join(current_path, 'db')
if not os.path.exists(data_path): # 没有文件夹
os.mkdir(data_path) # 创建文件
is_login = {'username': None}
def login_auth(func_name):
def inner(*args, **kwargs):
if is_login.get('username'):
res = func_name(*args, **kwargs)
return res
else:
print('请先登录')
login()
return inner
def register():
# 获取用户名和密码,第二次输入密码
username = input('username:').strip()
password = input('password:').strip()
second_pawd = input('second_pawd:').strip()
# 比较密码两次是否一致
if not password == second_pawd:
print('两次密码不一致')
return
# 拼接用户数据文件路径
file_path = os.path.join(data_path, f'{username}.json')
# 检验用户名是否存在>>>:检验文件路径是否存在
if os.path.isfile(file_path): # 文件名存在用户就存在
print('用户名已存在')
return # 结束函数运行
# 初始化用户数据
user_dict = {'username': username, 'password': password, 'balance': 15000, 'shop_car': {}}
with open(file_path, 'w', encoding='utf8') as f:
json.dump(user_dict, f, ensure_ascii=False)
print(f'{username}注册成功')
def login():
username = input('username:').strip()
password = input('password:').strip()
file_path = os.path.join(data_path, f'{username}.json')
if not os.path.isfile(file_path):
print('用户名不存在')
return
with open(file_path, 'r', encoding='utf8') as f:
user_dict = json.load(f)
if user_dict.get('password') == password:
print('登录成功')
# 修改全局变量
is_login['username'] = username
else:
print('密码错误')
@login_auth
def add_shop_car():
# 定义购物车数据(代码直接写死 也可以通过专门的商品文件便于后期维护更新)
good_list = [
['挂壁面', 3],
['印度飞饼', 22],
['极品木瓜', 666],
['土耳其土豆', 999],
['伊拉克拌面', 1000],
['董卓戏张飞公仔', 2000],
['仿真玩偶', 10000]
]
temp_shop_car = {}
while True:
for i, j in enumerate(good_list):
print("商品编号:%s | 商品名称:%s | 商品单价:%s" % (i, j[0], j[1]))
# 输入购买商品编号
choice = input('请输入您想要购买的商品编号或者输入y退出添加>>>:').strip()
# 想保存购物数据
if choice == 'y':
file_path = os.path.join(data_path, '%s.json' % is_login.get('username'))
with open(file_path, 'r', encoding='utf8') as f:
user_dict = json.load(f)
# 修改购物车数据
real_shop_car = user_dict.get('shop_car')
for good_name in temp_shop_car:
if good_name in real_shop_car:
real_shop_car[good_name][0] += temp_shop_car[good_name][0]
else:
real_shop_car[good_name] = temp_shop_car[good_name]
user_dict['shop_car'] = real_shop_car
# 重新写入文件
with open(file_path, 'w', encoding='utf8') as f:
json.dump(user_dict, f, ensure_ascii=False)
print('商品添加成功')
break
# 检验是否是纯数字
if not choice.isdigit():
print('必须输入纯数字')
continue
choice = int(choice)
# 校验数字范围
if not choice in range(len(good_list)):
print('编号超出范围')
continue
# 获取用户想购买的商品数据
target_good_list = good_list[choice]
target_good_name = target_good_list[0]
target_good_price = target_good_list[1]
# 获取用户想要购买数量
target_num = input('购买的数量:').strip()
if target_num.isdigit():
target_num = int(target_num)
# 确定了商量和数量 添加购物车 但是要考虑用户还可能购买其他商品
"""临时购物车字典里面可能已经存在一些商品 也可能是第一次购买"""
if target_good_name not in temp_shop_car:
temp_shop_car[target_good_name] = [target_num, target_good_price]
else:
temp_shop_car[target_good_name][0] += target_num
else:
print('商品个数必须是纯数字')
@login_auth
def cler_shop():
# 获取用户购物车数据
file_path = os.path.join(data_path,'%s.json'%is_login.get('username'))
# 获取购物车
with open(file_path, 'r',encoding='utf8') as f:
user_dict = json.load(f)
shop_car = user_dict.get('shop_car')
# 定义一个总价
total_money = 0
# 计算总价
for good_num, good_price in shop_car.values():
total_money += good_num * good_price
balance = user_dict.get('balance')
if balance > total_money:
rest_money = balance - total_money
user_dict['balance'] = rest_money
user_dict['shop_car'] = {}
with open(file_path,'w',encoding='utf8') as f:
json.dump(user_dict,f,ensure_ascii=False)
print(f'结算成功 今日消费{total_money} 余额{rest_money} 欢迎下次光临!!!')
else:
print('余额不够')
func_dict = {
'1': register,
'2': login,
'3': add_shop_car,
'4': cler_shop,
}
while True:
print('''
1.用户注册
2.用户登录
3.添加购物车
4.结算购物车
''')
choice = input('请输入功能编号:').strip()
if choice in func_dict:
func_name = func_dict.get(choice)
func_name()
else:
print('功能编号不存在')
分类:
python习题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人