#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
'''
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
'''
product_list = [['Iphone7',5800],
['Coffee',30],
['Python Book',99],
['Bike',199],
['ViVo X9',2499],
]
'''
购物车数据样式:
shopping_card={
'Iphone7':{'price':5800,'numbers':2}
}
'''
shopping_cart={}
current_userinfo={}
tag=True
while tag:
print('''1 注册\n2 登录\n3 购物\n4 账号解封
''')
choice=input('please input your choice(1 or 2 or 3 or 4): ').strip()
if choice == '1':
with open(r'userinfo', mode='r', encoding='utf8') as f_r:
username = input('please input yourname: ').strip(' #$%^*&!@')
for line in f_r:
line = line.strip('\n')
userinfo = line.split('|')
user_db = userinfo[0]
pass_db = userinfo[1]
blance_db = userinfo[2]
if username == user_db and len(username) == len(user_db):
print('%s 已存在,请直接登录' % username)
break
else: # 循环整个userinfo文件,没有username,则执行以下代码(else的子代码块会在循环结束后并且没有被break打断的情况下执行)
while True:
userpasswd1 = input('please input your passwd: ').strip()
userpasswd2 = input('please agin input your passwd: ').strip()
if userpasswd1 != userpasswd2:
print('密码前后不一致,请重新输入')
continue
else:
break
recharge = input('请输入充值金额: ').strip(' #$%^*&!@')
with open(r'userinfo', mode='a', encoding='utf8') as f_userinfo_a:
f_userinfo_a.write(
'{name}|{passwd}|{recharge}\n'.format(name=username, passwd=userpasswd1, recharge=recharge))
print('恭喜 %s 注册成功 \n首冲 %s !!!!' % (username, recharge))
elif choice == '2':
username=input('please input your username: ').strip(' @#$%^&*')
with open(r'userinfo',mode='r',encoding='utf8') as f_userinfo:
for line in f_userinfo:
line=line.strip('\n')
userinfo=line.split('|')
user_db=userinfo[0]
balance_db=userinfo[2]
if username == user_db:break
else:
print('%s 未注册,请选择1注册' %username)
continue
with open(r'locker_user',mode='r',encoding='utf8') as f_locker:
for line in f_locker:
line = line.strip('\n')
locker_user = line.split('\n')
locker_user = locker_user[0]
if username == locker_user:
print('%s 被锁定,选择4解封' %username)
tag=False
else:
error_counts = 1
while tag:
if error_counts > 3:
print('%s 输入次数过多,已被锁定' % username)
with open(r'locker_user', mode='r', encoding='utf8') as f_locker_r:
for locker_users in f_locker_r:
if username == locker_users: break
else:
with open(r'locker_user', mode='a', encoding='utf8') as f_locker_a:
f_locker_a.write(username+'\n')
break
userpasswd = input('please input your passwd: ').strip(' @#$%^&*')
if userinfo[1] == userpasswd:
print('%s 登录成功' %username)
current_userinfo={'name':username,'balance':balance_db}
print('当前用户信息为',current_userinfo)
break
else:
print('%s 密码错误,请重新输入' %username)
error_counts += 1
elif choice == '3':
if len(current_userinfo) == 0:
print('当前用户不能为空,请登录')
continue
while tag:
for index,product in enumerate(product_list): #对于一个可迭代的(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
print(index,product)
while tag:
# 开始买商品
item_number = input('请输入商品编号,输入q测退出: ').strip()
if item_number.isdigit():
item_number=int(item_number)
if item_number < 0 or item_number >= len(product_list):continue
item_name=product_list[item_number][0] #用户选择的商品名称
item_price=product_list[item_number][1] #用户选择的商品价格
current_balance=int(current_userinfo['balance']) #将余额有字符串类型转为int类型
if current_balance > item_price: #判断余额是否够买此商品
if item_name in shopping_cart:
shopping_cart[item_name]['numbers']+=1 #如果购物车已存在此商品,则商品数量+1
else:
shopping_cart[item_name]={'price':item_price,'numbers':1} #添加到购物车
current_balance-=item_price # 余额=身上的钱-商品价格
current_userinfo['balance']=current_balance
print('成功添加商品'+ item_name + "到购物车"+'\n' '你的余额为 %s' %current_balance)
else:
print('太贵了,买不起,产品价格是{price},你还差{lack_price}'.format(
price=item_price,
lack_price=item_price-current_balance)
)
print(shopping_cart)
elif item_number == 'q':
# 打印购物车明细
print("""
---------------------------------已购买商品列表---------------------------------
id 商品 数量 单价 总价
""")
total_cost = 0
for i, key in enumerate(shopping_cart):
print('%21s%17s%18s%18s%18s' % ( #%17s 从第一个字符到第二个字符之间经历了17个空格
i,
key,
shopping_cart[key]['numbers'],
shopping_cart[key]['price'],
shopping_cart[key]['price'] * shopping_cart[key]['numbers']
))
total_cost += shopping_cart[key]['price'] * shopping_cart[key]['numbers'] #单个商品的累计总价
print('''
你的总花费为: %s
你的余额为: %s
''' %(total_cost,current_balance)
)
while tag:
#确认是否结算购物车商品
account=input('请输入y/Y/N/n确认是否结算: ').strip()
if account not in ['y','Y','N','n']:continue
if account in ['y','Y']:
# 更新当前用户的余额
with open(r'userinfo',mode='r',encoding='utf8') as f_src,\
open(r'userinfo.swap',mode='w',encoding='utf8') as f_dst:
for line in f_src:
if line.startswith(username):
l=line.strip('\n').split('|')
l[-1]=str(current_balance)
line='|'.join(l)+'\n'
f_dst.write(line)
os.remove('userinfo')
os.rename('userinfo.swap','userinfo')
print('恭喜你购买成功,请耐心等待发货')
shopping_cart={} #清空购物车
current_userinfo={} #清空登录账号信息,安全退出
tag=False
else:
print('非法的商品编号,请重新输入')
continue
elif choice == '4':
username = input('please input yourname: ').strip(' #$%^*&!@')
with open(r'locker_user', mode='r', encoding='utf8') as f_r,\
open(r'locker_user.swap', mode='w', encoding='utf8') as f_w:
for line in f_r:
line = line.strip('\n')
if line.startswith(username):
continue
f_w.write(line + '\n')
else:
print('%s 已解封,可正常登录' %username)
os.remove(r'locker_user')
os.rename(r'locker_user.swap', r'locker_user')
else:
print('非法操作,请重新输入')