1. 用户输入帐号密码进行登陆
2. 用户信息保存在文件内
3. 用户密码输入错误三次后锁定用户
主要采用循环语句和条件语句进行程序流程的控制,加入文件的读写操作
while True:
choice = input("登陆L 注册R 退出Q:").strip()
#用户登录流程
if choice.lower() == 'l':
l_flag = False
count = 1
tmp = ''
while True:
user_name =input("请输入用户名(或者'q'退出):").strip()
if not user_name:continue
if user_name == 'q':
print("退出成功!")
exit()
user_pwd = input("请输入用户密码(或者'q'退出):").strip()
if not user_pwd:
print("密码不能为空,请重新输入!")
continue
if user_pwd == 'q':
print("退出成功!")
exit()
with open("locked_id",mode="r",encoding="utf8") as f_locked:
for line in f_locked:
if line.startswith("username:") and user_name in line and len(user_name)!=0:
print("该用户已经被锁定,请联系管理员!")
exit()
with open("user_id",mode="r",encoding="utf8") as f_reed:
for line in f_reed:
if line.startswith("username:") and user_name in line and len(user_name) != 0:
l_flag = True
tmp = line
if l_flag:
if tmp.split(":")[2].strip() == user_pwd:
print("用户登录成功!")
l_flag = False
exit()
elif count >= 3:
with open("locked_id",mode="a",encoding="utf8") as f_locked:
f_locked.write("\nusername:"+user_name)
print("您的密码错误三次,用户被锁定!")
l_flag =False
exit()
else:
count += 1
l_flag =False
print("密码错误,请重新输入!")
continue
else:
print('用户名不存在,请重新登录!') #用户注册流程
if choice.lower() == 'r':
r_flag = False #注册过程标志位
while True:
new_user_name =input("请输入注册用户名(或者'q'退出):").strip()
if not new_user_name:continue #用户名为空开始下一个循环
if new_user_name == 'q':
print("退出成功!")
exit()
new_pwd = input("请输入用户密码且不少于6位(或者'q'退出):").strip()
if new_pwd == 'q':
print("退出成功!")
exit()
if len(new_pwd) < 6:
print('密码不能为空且不少于6位!')
continue
with open("user_id",mode="r+",encoding="utf8") as f:
f.seek(0)
for line in f:
if line.startswith("username:") and new_user_name in line: #判断是否已经有该用户
print("该用户已经被注册!")
r_flag = True
break
if not r_flag:
f.write("\nusername:" + new_user_name)
f.write("\t|password:" + new_pwd)
print("新用户注册成功!")
r_flag = False
break #退出流程
if choice.lower() == 'q':
print("退出成功!")
exit()
模拟登陆代码