编写用户登录接口,文件相关
作业一:编写用户登录接口
#1、输入账号密码完成验证,验证通过后输出"登录成功"
#2、可以登录不同的用户
#选做功能:同一账号输错三次锁定,(提示:锁定的用户存入文件中,这样才能保证程序关闭后,该用户仍然被锁定)
#存放账户
namelist=[]
#存放密码
pwdlist=[]
#存放黑名单用户
blacklist=[]
tag = True
while tag:
inp_name = input("请输入用户名:")
#1.获取用户名,密码
with open ("user.txt",mode="r+",encoding="utf-8")as fp:
data = fp.readlines()
#print(data)
#提取文件里的账户和密码
for i in data:
name,pwd=i.strip().split(":")
namelist.append(name)
pwdlist.append(pwd)
#2.判断是不是存在该用户
if inp_name in namelist:
#判定是不是黑名单用户:
with open("black.txt", mode="a+", encoding="utf-8")as fp:
fp.seek(0)
lst = fp.readlines()
for i in lst:
blacklist.append(i.strip())
if inp_name in blacklist:
print("不好意思,账户已锁定")
else:
#允许用户输入账号密码
num = namelist.index(inp_name)
times=0
while times < 3:
inp_pwd = input("请输入密码:")
if inp_pwd == pwdlist[num]:
print("登录成功")
tag = False
break
else:
print("密码错误,还有%s次机会输入"%(2-times))
if times == 2:
print("输错3次,账号已锁定")
with open ("black.txt",mode="a+",encoding="utf-8")as fp:
fp.write("%s\n" % inp_name)
times+=1
else:
print("用户不存在")
作业二:编写程序实现用户注册后(注册到文件中),可以登录(登录信息来自于文件)
提示:
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('输入的命令不存在')
while True:
msg = """
0 退出
1 登录
2 注册
"""
print(msg)
cmd = input("请输入命令编号: ").strip()
if not cmd.isdigit():
print("必须输入命令编号的数字")
continue
if cmd == "0":
break
elif cmd == "1":
# 存放账户
accountlist = []
# 存放密码
pwdlist = []
tag = True
while tag:
username = input("请输入用户名:")
print(username)
# 1.获取用户名密码等数据
with open("user.txt", mode="r+", encoding="utf-8")as fp:
lst = fp.readlines()
# 提取文件里的账号密码
for i in lst:
account, pwd = i.strip().split(":")
accountlist.append(account)
pwdlist.append(pwd)
# 2.判断是否存在该用户
if username in accountlist:
num = accountlist.index(username)
times = 0
while times < 3:
pwd = input("请输入您的密码:")
if pwd == pwdlist[num]:
print("登录成功")
tag = False
break
else:
print("密码错误,你还剩下%s次机会" % (2 - times))
# 3.账号输入3次锁定
if times == 2:
print("密码错误三次,账户已锁定")
times += 1
else:
print("该用户不存在")
elif cmd == "2":
accountlist = []
name = input("请输入登录名:").strip()
with open ("user.txt", mode="r+", encoding="utf-8")as fp:
lst = fp.readlines()
# 提取文件里的账号
for i in lst:
account, pwd = i.strip().split(":")
accountlist.append(account)
if name in accountlist:
print("用户名已存在,请直接登录")
break
else:
pwd = input("请输入密码: ").strip()
break
with open("user.txt",mode="a+",encoding="utf-8")as fp:
fp.write(name+":"+pwd+"\n")
else:
print('输入的命令不存在')