python学习 阶段性小项目 atm+购物车 面条版
atm不分文件格式的, 直接一条线写下去,面条版
import json
import os
import datetime
# 参考atm的需求写一份不分模块的简单atm
# 定义一个user字典用于存放登陆状态,None为未登录,如果username存在值就证明已登录
user = {'username':None}
shopping_car_dict = {} # 定义一个空字典用于暂时存放我们要买的东西
goods_count = [0] # 这个是用于记录当前用户一次购物的消费金额
# 这个是商品列表
goods_list = [
['Iphone7', 5800],
['Coffee', 30],
['疙瘩汤', 10],
['Python Book', 99],
['Bike', 199],
['ViVo X9', 2499],
]
# 定义一个函数用于向json文件中写数据
def wr_json(name,userinfo):
if not os.path.isdir('json'):
os.mkdir('json')
user_path = os.path.join(f'json/{name}.json')
with open(user_path,'w',encoding='utf8') as fw:
json.dump(userinfo,fw)
# 定义一个函数用于读取用户json文件的信息
def rd_json(name):
if not os.path.isdir('json'):
os.mkdir('json')
user_path = os.path.join(f'json/{name}.json')
with open(user_path,'r',encoding='utf8') as fr:
data = json.load(fr)
return data
# 定义一个money 变量用于存放用户当前的余额数
def logout():
print('这是退出功能呢')
if user['username']:
userinfo = rd_json(user['username'])
print(f"亲爱的用户:{user['username']} 你当前剩余金额为:{userinfo['money']}\n"
f"已为你退出当前账号了!")
userinfo['log'].append(f"{str(datetime.datetime.now())[:-7]} 你执行了退出系统的操作")
wr_json(user['username'],userinfo)
user['username'] = None
else:
print('当前尚无用户登录,无需执行退出功能')
def login():
print('这是登陆功能')
if not user['username']:
username = input('请输入你的用户名:')
pwd = input('请输入你的密码:')
# user_login_info = f'{username}-{pwd}'
if os.path.exists(f'json/{username}.json') :
userinfo = rd_json(username) # dict
```
if username == userinfo['username'] and pwd == userinfo['pwd']:
user['username'] = username
print(f'登陆成功,你当前剩余金额为:{userinfo["money"]}')
userinfo['log'].append(f'{str(datetime.datetime.now())[:-7]} 登陆了系统')
wr_json(username,userinfo)
print(userinfo)
else:
print('登陆失败')
else:
print('登陆失败')
else:
print(f"当前已登录了 {user['username']} 账号,如需切换账号,请执行退出功能")
```
def register():
print('这是注册功能')
if not user['username'] :
username = input('请输入你要注册的用户名:')
pwd = input('请输入你要注册的密码:')
money = 15000
date = str(datetime.datetime.now())[:-7]
user_reg_info = {'username': username, 'pwd': pwd, 'money': money, 'log': [f'{date}该用户注册了账号'],'history':[],'shopping_log':{}}
print(user_reg_info)
wr_json(username, user_reg_info)
print('恭喜你注册成功!')
else:
print(f"当前已登录了 {user['username']} 账号,如需切换账号,请执行退出功能")
def slect_balance():
print('这是查看余额功能')
if user['username']:
userinfo = rd_json(user['username'])
print(f'亲爱的{userinfo["username"]} 你当前的余额为:{userinfo["money"]}')
# 可扩充余额不足功能
userinfo['log'].append(f"{str(datetime.datetime.now())[:-7]} 执行了查询余额操作")
wr_json(user['username'],userinfo)
else:
print('当前尚无用户登录,请先登录后再查询')
login()
def transfer():
print('这是转账功能')
if user['username']:
userinfo = rd_json(user['username'])
balance = userinfo['money']
print(f'亲爱的{userinfo["username"]} 你当前的可转账金额为:{balance}')
other_name = input('请输入你要转账的用户名:')
transfer_num = input('请输入转账金额:')
other_info_path = f'json/{other_name}.json'
if os.path.exists(other_info_path) :
if int(transfer_num) > balance:
print('转账失败:你输入转账的金额大于你当前余额')
userinfo['log'].append(f"{str(datetime.datetime.now())[:-7]} 向用户{other_name}转账失败:你输入转账的金额大于你当前余额")
else:
userinfo['money'] = balance - int(transfer_num)
print(f'你已成功向用户{other_name}转账{transfer_num}元,当前余额为:{userinfo["money"]}元')
userinfo['history'].append(f'{str(datetime.datetime.now())[:-7]} 你已成功向用户{other_name}转账{transfer_num}元,当前余额为:{userinfo["money"]}元')
other_info = rd_json(other_name)
other_info['money'] += int(transfer_num)
other_info['history'].append(f'{str(datetime.datetime.now())[:-7]} 用户{user["username"]}向你的账户转入{transfer_num}元')
wr_json(other_name,other_info)
wr_json(user['username'],userinfo)
else:
print('你输入的转入用户不存在,请重新输入')
else:
print('当前尚无用户登录,请先登录后再查询')
login()
def repayment():
print('这是还款功能')
if user['username']:
user_info = rd_json(user['username'])
user_money = user_info['money']
if user_money < 15000 :
choice_repay = input(f'当前账户目前欠款:{15000-user_money}元,请问是否还款(是输入y,否输入n):')
if choice_repay == 'y':
repay_money = input('请输入还款金额:')
user_info['money'] = int(repay_money) + user_money
print(f'恭喜你还款{repay_money}成功!当前账户可用余额:{user_info["money"]}')
user_info['history'].append(f'{str(datetime.datetime.now())[:-7]} 你完成了还款{repay_money}元操作,当前账户可用余额:{user_info["money"]}元')
wr_json(user['username'], user_info)
elif choice_repay == 'n':
print('穷逼,你选择了不还款。欠钱不还,会被打死的!')
else:
print('当前账户无欠款哟,棒棒哒,赶紧去消费吧')
else:
print('当前尚无用户登录,请先登录后再查询')
login()
def withdrawal():
print('这是取款功能')
if user['username']:
user_info = rd_json(user['username'])
user_money = user_info['money']
if user_money > 0 :
choice_withd = input(f'当前账户目前剩余可用金额:{user_money}元,请问是否执行取款操作(是输入y,否输入n):')
if choice_withd == 'y':
withd_money = input('请输入取款金额:')
user_info['money'] = user_money - int(withd_money)
print(f'恭喜你取款{withd_money}成功!当前账户可用余额:{user_info["money"]}')
user_info['history'].append(f'{str(datetime.datetime.now())[:-7]} 你完成了取款{withd_money}元操作,当前账户可用余额:{user_info["money"]}元')
wr_json(user['username'], user_info)
elif choice_withd == 'n':
print('你选择了不取款,那你进来干啥的??')
else:
print('当前账户金额无可用金额,请先去完成还款操作,再来取款')
else:
print('当前尚无用户登录,请先登录后再查询')
login()
def ckeck_water():
print('这是查看流水功能' )
if user['username']:
user_info = rd_json(user['username'])
user_history = user_info['history']
user_shopping_log = user_info['shopping_log']
choice = input('查看交易流水请按1,购物记录请按2:')
if choice == '1':
print('你当前账户的交易流水如下:')
if user_history != {}:
for index, history in enumerate(user_history):
print(f'{index + 1}. {history}')
else:
print('当前账户尚无交易流水')
user_info['log'].append(f'{str(datetime.datetime.now())[:-7]} 你执行了查询流水的操作')
elif choice == '2':
print('你当前账户的购物记录如下:')
if user_shopping_log != []:
for log, shopping_log in user_shopping_log.items():
print(f'{log}:{shopping_log}')
else:
print('当前账户尚无购物记录')
user_info['log'].append(f'{str(datetime.datetime.now())[:-7]} 你执行了查询购物记录的操作')
wr_json(user['username'],user_info)
else:
print('当前尚无用户登录,请先登录后再查询')
login()
def shopping():
print('这是购物功能')
if user['username']:
user_info = rd_json(user['username'])
user_info['log'].append(f'{str(datetime.datetime.now())[:-7]} 你执行了购物功能')
wr_json(user['username'],user_info)
print(f'亲爱的{user["username"]},欢迎你来到购物天堂。我们有如下商品:')
while True :
for ind, goods in enumerate(goods_list):
print(f'商品编号{ind} 对应的商品是:{goods[0]} 它的售价为:{goods[1]}')
goods_ind = input('请输入你要购买的商品的编号(退出购物请按q):')
if goods_ind == 'q':
print('你选择了退出购物功能')
break
goods_num = input('请输入购买数量:')
goods_name = goods_list[int(goods_ind)][0] # 当前选择购买的商品名
goods_prize = goods_list[int(goods_ind)][1] # 当前购买商品的价格
if goods_name in shopping_car_dict:
shopping_car_dict[goods_name] += int(goods_num)
else:
shopping_car_dict[goods_name] = int(goods_num)
print(f'你刚才向购物车中添加了:{goods_name} {goods_num}个')
goods_count[0] += goods_prize * int(goods_num) # 计算购买花了多少钱
```
else:
print('当前尚无用户登录,请先登录后再查询')
login()
```
def shopping_car():
print('这是购物车功能')
if user['username'] :
user_info = rd_json(user['username'])
balance = user_info['money']
user_info['log'].append(f'{str(datetime.datetime.now())[:-7]} 你执行了购物车功能')
wr_json(user['username'],user_info)
print(f'当前购物车有如下商品,共计{goods_count[0]}元:')
print(shopping_car_dict)
for goods_name, goods_num in shopping_car_dict.items():
print(f'商品:{goods_name} 有{goods_num}件')
while True:
choice = input('请做出你的选择,结账请输入p,需要删除商品请按d,需要添加某件商品请按a,需要清空购物车请按c,退出结账请按q:')
if choice == 'p':
if goods_count[0] > balance:
print(f'对不起,本次消费金额大于你当前剩余余额(相差:{goods_count[0] - balance}元),请充值之后或者删除一些商品后再来结账')
else:
print(f'你好,你本次一共消费{goods_count[0]}元,当前剩余余额:{balance - goods_count[0]}元,欢迎下次惠顾!')
user_info['money'] = balance - goods_count[0]
user_info['history'].append(
f'{str(datetime.datetime.now())[:-7]} 你在购物天堂消费了{goods_count[0]}元,当前余额为:{user_info["money"]}元')
user_info['shopping_log'].setdefault(
f'{str(datetime.datetime.now())[:-7]} 你在购物天堂消费了{goods_count[0]}元,购买了这些东西', shopping_car_dict)
wr_json(user['username'], user_info)
shopping_car_dict.clear()
goods_count[0] = 0
break
if choice == 'd':
print('你选择了删除商品的功能:')
del_goods = input('请输入你要删除的商品名:')
del_num = input('请选择你要删除的数量:')
shopping_car_dict[del_goods] -= int(del_num)
print(f'你刚才删除{del_goods} {del_num}件')
del_goods_prize = 0
for i in goods_list:
if del_goods in i:
del_goods_prize = i[1]
break
goods_count[0] -= int(del_num) * del_goods_prize
elif choice == 'a':
print('你选择了添加商品的功能:')
add_goods = input('请输入你要添加的商品名:')
add_num = input('请选择你要添加的数量:')
shopping_car_dict[add_goods] += int(add_num)
print(f'你刚才添加了{add_goods} {add_num}件')
add_goods_prize = 0
for i in goods_list:
if add_goods in i:
add_goods_prize = i[1]
break
goods_count[0] += int(add_num) * add_goods_prize
elif choice == 'c':
print('你选择了清除购物车的功能:')
shopping_car_dict.clear()
goods_count[0] = 0
print(f'清除成功,当前购物车中已无商品')
elif choice == 'q':
print('你选择了退出购物车功能')
break
else:
print('当前尚无用户登录,请先登录后再查询')
login()
func_dict = {
'0': logout,
'1': login,
'2': register,
'3': slect_balance,
'4': transfer ,
'5': repayment,
'6': withdrawal,
'7': ckeck_water,
'8': shopping,
'9': shopping_car,
'q': exit
}
FUNC_MSG = '''
'0': '注销',
'1': '登录',
'2': '注册',
'3': '查看余额',
'4': '转账',
'5': '还款',
'6': '取款',
'7': '查看流水',
'8': '购物',
'9': '购物车',
'q': '退出'
'''
while True:
print(FUNC_MSG)
choice_num = input('请选择你要进行的操作:')
if choice_num in '0123456789q':
func_dict[choice_num]()
else:
print('你的输入有误请重新输入')