51_work--购物车

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了51_work--购物车相关的知识,希望对你有一定的参考价值。

import json
import os
import datetime

info = ‘‘‘
*************欢迎光临****************
* *
* 1.按"A"或"a"注册 *
* 2.按"L"或"l"登陆 *
* 3.按"Q"或"q"退出 *
***********************************
‘‘‘
error_info = ‘输入错误,请重新输入!‘


def save_account(message, filename=‘message.json‘):
with open(filename, ‘w‘) as f:
json.dump(message, f)


def load_message(filename=‘message.json‘):
with open(filename) as f:
message = json.load(f)
return message


def add_user():
message = load_message(‘message.json‘)
while True:
username = input(‘请输入用户名>>>:‘).strip()
if username in message:
print(‘该用户名已存在,请重新输入!‘)
else:
break
while True:
pwd1 = input(‘请输入密码>>>:‘)
pwd2 = input(‘请再次输入密码>>>:‘)
if pwd1 != pwd2:
print(‘两次密码不一样,请重新输入>>>:‘)
else:
print(‘账户创建成功,请登录!‘)
message[username] = {‘pwd‘: pwd1, "balance": 0, ‘shopping_list‘: [], ‘shopping_time‘: None}
save_account(message)
break

def login():
message = load_message(‘message.json‘)
locklist = load_message(‘locklist.json‘)
print(‘Welcom to shopping system!‘)
while True:
account = input(‘请输入你的用户名(按q退出系统)>>>:‘)
if account in locklist:
print(‘抱歉,你的账号已被锁定!‘)
log_out()
elif account == ‘q‘:
log_out()
elif account in message:
count = 0
while count < 3:
pwd = input(‘请输入密码>>>:‘)
if pwd == message[account][‘pwd‘]:
while True:
account_balance = get_balance(account)
print(‘你的账户余额为\033[32m%d\033[0m‘ % account_balance)
command = input(‘按h查询购物历史,按s开始购物,按r充值>>>:‘)
if command == ‘h‘:
if message[account][‘shopping_time‘] != None:
get_shopping_history(account)
else:
print(‘您在本商城没有购物历史!‘)
elif command == ‘s‘:
shopping(account) # 开始购物
elif command == ‘r‘:
recharge(account)
else:
print(error_info)
else:
count += 1
print(‘密码错误,你还有%d次机会‘ % (3 - count))
locklist.setdefault(account)
print(‘你的账号已被锁定!‘)
save_account(locklist, ‘locklist.json‘)
log_out()
else:
print(‘该用户不存在!按b返回上一层或按q退出‘)


def log_out(account=None):
if account != None:
get_shopping_history(account)
exit(‘Thank you so much for coming!‘)


def get_balance(account):
message = load_message(‘message.json‘)
account_balance = message[account][‘balance‘]
return account_balance


def shopping(account):
goods = {‘家电类‘: {‘电视‘: {‘小米电视‘: 3999, ‘乐视电视‘: 4299},
‘空调‘: {‘格力空调‘: 8999, ‘海尔空调‘: 6000},
‘冰箱‘: {‘美的冰箱‘: 5099, ‘西门子冰箱‘: 4599}},
‘3C类‘: {‘电脑‘: {‘联想笔记本‘: 6888, ‘mac air‘: 8009},
‘手机‘: {‘小米5‘: 1999, ‘iPhone6‘: 5299}},
‘生活类‘: {‘鞋子‘: {‘NIKE篮球鞋‘: 899, ‘安踏‘: 399},
‘T恤‘: {‘森马‘: 89, ‘真维斯‘: 75, ‘优衣库‘: 97}}}
while True:
for each in enumerate(goods.keys()):
print(each) # 打印第一级菜单(第一级keys)
choose = input(‘请输入您要选择的物品分类名(输入q退出):‘).strip()
str1 = ‘‘
if choose in goods:
for each in enumerate(goods[choose].keys()):
print(each) # 打印第二级菜单(第二级keys)
str1 += (each[1] + ‘\n‘)
str1 += ‘:‘
while True:
c_name = input("请输入您要选择的%s分类名称(输入b返回上级菜单输入q退出):\n%s"
% (choose, str1)).strip()
str2 = ‘‘
if c_name == ‘b‘:
break
elif c_name == ‘q‘:
log_out(account)
elif c_name in goods[choose]:
for each in goods[choose][c_name].keys():
print(each, goods[choose][c_name][each]) # 打印第三级菜单(物品菜单和价格)
str2 += (each + ‘\n‘)
str2 += ‘:‘
while True:
p_name = input("请输入您要购买的物品名称(输入b返回上级菜单,q退出,h查询购物清单):\n%s"
% str2).strip()
if p_name == ‘b‘:
break
elif p_name == ‘q‘:
log_out(account)
elif p_name == ‘h‘:
database = load_message()
if database[account][‘shopping_time‘] != None:
get_shopping_history(account)
else:
print(‘您在本商城没有购物历史!‘)
elif p_name in goods[choose][c_name]:
while True:
num = input(‘请输入您要购买的数量:‘).strip()
if num.isdigit():
num = int(num)
account_balance = get_balance(account) # 获取物品单价
price = (goods[choose][c_name][p_name]) * num # 单价*数量
if account_balance >= price: # 余额大于商品价格才能购买
set_balance(account, price)
print(‘您成功购买%d件商品:%s!‘ % (num, p_name))
set_shopping_list(account, p_name, num) # 将所购买的物品保存到文件
account_balance = get_balance(account) # 获取账户余额
print(‘您的账户余额为\033[31m%d\033[0m元‘ % account_balance)
set_shopping_time(account)
break # 购买完返回上级菜单
else:
print(‘您的账户余额不足,请您及时充值!‘)
break # 余额不足返回上级菜单
else:
print(error_info)
else:
print(error_info)

else:
print(‘输入错误,请重新输入‘)

elif choose == ‘q‘:
log_out(account)
else:
print(‘输入错误,请重新输入‘)


def get_shopping_history(account):
database = load_message()
history = database[account][‘shopping_list‘]
l1 = []
for each in history:
if each not in l1:
l1.append(each)
for each in l1:
count = history.count(each)
date = get_datetime(account)
print(‘您于%s购买了%d件%s‘ % (date, count, each))


def set_shopping_time(account):
message = load_message()
d1 = datetime.datetime.now()
d2 = d1.strftime(‘%Y-%m-%d %H:%M:%S‘)
message[account][‘shopping_time‘] = d2
save_account(message)


def get_datetime(account):
message = load_message()
data = message[account][‘shopping_time‘]
return data

def set_shopping_list(account, c_name, num):
message = load_message()
for i in range(num):
message[account][‘shopping_list‘].append(c_name)
save_account(message)

def set_balance(account, price):
message = load_message()
message[account][‘balance‘] -= price
save_account(message)


def recharge(account):
message = load_message()
while True:
num = input(‘请输入您要充值的金额:‘)
if num.isdigit():
message[account]["balance"] += int(num)
save_account(message)
account_balance = get_balance(account)
print(‘您已成功充值,您的余额为\033[32m%d\033[0m元‘ % account_balance)
return None
else:
print(‘您的输入有误,请重新输入!‘)

def main():
while True:
print(info)
commend = input(‘请输入操作指令>>>:‘)
if commend.upper() == ‘A‘:
add_user()
elif commend.upper() == ‘L‘:
login()
elif commend.upper() == ‘Q‘:
log_out()
else:
print(error_info.center(40,‘-‘))

if __name__ == "__main__":
main()

以上是关于51_work--购物车的主要内容,如果未能解决你的问题,请参考以下文章

基于session的简易购物车引发的问题

python练习-跳出多层循环和购物车

认知物联网时代,17000家企业用Watson刷新购物体验

购物车小代码

python 改良购物车

简单购物车