Python day11
#简易购物车
function_msg = '''
1 登录
2 注册
3 注销
4 购物
5 购物车
q 退出'''
goods_dict = {
'0': "芭比娃娃",
'1': "变形金刚",
'2': "psp游戏机",
'3': "奥特曼",
'4': "遥控飞机",
'5': "chongqiwawa",
}
goods_msg = '''
0 芭比娃娃
1 变形金刚
2 psp游戏机
3 奥特曼
4 遥控飞机
5 chongqiwawa'''
user_info_list = []
goodscar_dict = {}
def get_inp():
'''用户交互'''
username_inp = input('请输入用户名:')
pwd_inp = input('请输入密码:')
return username_inp,pwd_inp
def login():
'''登录功能'''
if user_info_list:
print('已登录!!')
return
login_count = 0
while login_count < 3:
username_inp,pwd_inp = get_inp()
with open('user_info.txt', 'r', encoding='utf8') as fr:
for user_info in fr:
user_info = user_info.strip()
username, pwd = user_info.split(':')
if username_inp == username and pwd_inp == pwd:
print('登陆成功!')
user_info_list.append(username_inp)
return
else:
print('账号密码错误,请重新输入!')
login_count += 1
def register():
'''注册功能'''
register_count = 0
while register_count <1:
username_inp, pwd_inp = get_inp()
if ':' in username_inp or ':' in pwd_inp:
print('用户名密码中不能含有":",请重新输入!')
else:
with open('user_info.txt', 'a', encoding='utf8') as fa:
fa.write(f'{username_inp}:{pwd_inp}\n')
fa.flush()
print('注册成功!')
register_count = 1
def logout():
'''注销用户'''
if not user_info_list:
print('请先登录!!')
return
user_info_list.clear()
print('您已注销登录!!')
def shopping():
'''购物'''
if not user_info_list:
print('请先登录!!')
return
goods_count = 0
while goods_count < 1:
print(goods_msg)
get_goods = input('请选择要购买的商品:')
if not get_goods in goods_dict:
print('请选择正确的商品!')
continue
else:
goods = goods_dict[get_goods]
if goods in goodscar_dict :
goodscar_dict[goods] += 1
print(f'{goods}已加入购物车,\n购物车:{goodscar_dict}')
return
else:
goodscar_dict[goods] = 1
print(f'{goods}已加入购物车,\n购物车:{goodscar_dict}')
return
def shoppingcar():
'''购物车'''
if not user_info_list:
print('请先登录!!')
return
print(f'恭喜{user_info_list}已购买{goodscar_dict},祝您购物愉快!!')
goodscar_dict.clear()
function_dic = {
'1': login,
'2': register,
'3': logout,
'4': shopping,
'5': shoppingcar
}
while 1:
print(function_msg)
if user_info_list:
print(f'{user_info_list},欢迎您的光临!!')
function_choice = input('请选择功能:')
if function_choice == 'q':
break
if not function_choice in function_dic:
print('请选择以上的功能!')
continue
function_dic[function_choice]()