周末作业:文件处理

周末综合作业:
# 2.1:编写用户登录接口
#1、输入账号密码完成验证,验证通过后输出"登录成功"
#2、可以登录不同的用户
#3、同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)

解题:

new_dict = {'egon':'123','lxx':'234','alex':'456'}
count = 0
while count < 3:
username = input('请输入账号:').strip()
password = input('请输入密码:').strip()
if username in new_dict:
if password == new_dict.get(username):
print('登陆成功')
break
else:
print('密码错误')
count += 1
print('密码输错%s次' % count)
else:
print('账号错误')
if count == 3:
with open('user.txt',mode='at',encoding='utf-8') as f:
f.write('被锁定的用户为:{}\n'.format(username))

# 2.2:编写程序实现用户注册后,可以登录,
提示:
while True:
msg = """
0 退出
1 登录
2 注册
"""
print(msg)
cmd = input('请输入命令编号>>: ').strip()
if not cmd.isdigit():
print('必须输入命令编号的数字,傻叉')
continue

if cmd == '0':
break
elif cmd == '1':
# 登录功能代码(附加:可以把之前的循环嵌套,三次输错退出引入过来)
pass
elif cmd == '2':
# 注册功能代码
pass
else:
print('输入的命令不存在')

# 思考:上述这个if分支的功能否使用其他更为优美地方式实现

解题:

#  定义一个注册功能函数register
def register():
inp_name = input('请输入你要注册的账号:').strip()
inp_pwd = input('请为你的账号设置密码:').strip()
file_name = 'db.txt'
with open(r'{}'.format(file_name), mode='rt', encoding='utf-8') as f:
users = f.readlines()
user_names = []
for user in users:
user_name, *_ = user.strip().split(':')
user_names.append(user_name)
if inp_name in user_names:
print('账号已存在,注册失败。')
else:
with open(r'{}'.format(file_name), 'at', encoding='utf-8') as f:
f.write('{}:{}\n'.format(inp_name, inp_pwd))
print('注册成功。')


# 定义一个登录功能函数log_in
def log_in():
count = 0
flag = True
while flag:
inp_name = input('请输入你的账号:').strip()
inp_pwd = input('请输入你的密码:').strip()
with open(r'locked_name.txt', mode='rt', encoding='utf-8') as f:
locked_names = f.readlines()
for locked_name in locked_names:
locked_name = locked_name.strip()
if inp_name == locked_name:
print('账号 {} 已锁定。'.format(inp_name))
flag = False
break
else:
with open(r'db.txt', mode='rt', encoding='utf-8') as f:
users = f.readlines()
user_info = {}
for user in users:
user_name, password = user.strip().split(':')
user_info[user_name] = password
if inp_name in user_info:
if inp_pwd == user_info.get(inp_name):
print('登录成功。')
break
else:
print('密码错误。')
count += 1
if count == 3:
print('账号 {} 3次输入密码错误,账号已锁定。'.format(inp_name))
with open(r'locked_name.txt', mode='at', encoding='utf-8') as f:
f.write('{}\n'.format(inp_name))
break
else:
print('你输入的账号不存在,请重新输入。')


# 主程序部分
while True:
msg = """
0 退出
1 登录
2 注册
"""
print(msg)
cmd = input('请输入命令编号>>: ').strip()
cmd_dic = {
'1': log_in,
'2': register
}
if cmd == '0':
break
elif cmd in cmd_dic:
cmd_dic.get(cmd)()
else:
print('只能输入命令编号的数字,傻叉')

猜你喜欢

转载自www.cnblogs.com/python--wang/p/12501754.html
今日推荐