题目选自 Alex Python自动化开发之路的题目,我是从C++转学Python的,编写的水平有限,轻喷。

  • 输入用户名密码
  • 认证成功后显示欢迎信息
  • 输错三次后锁定

首先应该有2个txt文件,包含用户名密码的user.txt和包含被锁定文件的lock.txt(用户名自己设定即可)

我的user.txt文件每行有一个用户名和密码 中间用空格隔开

类似:

zhu 123456

zhang 123456

lock.txt每行有一个用户名

代码如下:

 # Author:Zhu

 count = 0
while count < 3:
username = input("请输入用户名: ")
if username == '':
exit("用户名输入错误,程序退出...")
lock_file = open("lock.txt", 'r')
lockf = lock_file.readlines()
# 锁定账号的比对
for line in lockf:
if username in line.split(): # 注意换行符的分割
exit("\033[31;1m你的账户[%s]已经被锁定,请联系管理员\033[0m" %username)
lock_file.close()
password = input("请输入密码:")
login_check = open('user.txt', 'r')
loginf = login_check.readlines()
# 登录账号和密码的对比
for line in loginf:
line = line.split()
if username == line[0] and password == line[1]:
exit("\033[32;1m登录成功!欢迎您,%s\033[0m" %username)
elif username == line[0] and password != line[1]:
pass_count = 0
while pass_count < 3:
print("\033[31;1m您的密码错误,剩余尝试次数[%s]次\033[0m" %(2-pass_count))
password_r = input("请重新输入密码:")
pass_count += 1
if password_r == line[1]:
exit("\033[32;1m登录成功!欢迎您,%s\033[0m" % username)
if pass_count == 2:
print("\033[31;1m你的密码输入错误次数已经达到最大,账号[%s]被锁定\033[0m" %username)
in_lock = open("lock.txt", 'a+')
in_lock.write(username)
in_lock.write('\n')
in_lock.close()
exit() else:
print("您的账号[%s]不存在,请注册" %username) count += 1
if count == 3:
print("您已经尝试3次,登录失败")
else:
print("请重新输入:")

为了配合登录界面功能的实现,我又写了一个注册界面的编写

  Author:Zhu

 def username_check(username):
while True:
file_check = open('user.txt', 'r')
for line in file_check.readlines():
line = line.split()
if username == line[0]:
print("账号已经存在,请重新输入账号:")
return 0
else:
print("可以注册")
return 1
break while True:
username = input("请输入您的账户名:")
if username_check(username) == 1:
break
else:
continue
while True:
password_first = input("请输入您的密码: ")
password_second = input("请再次输入您的密码")
if password_first == password_second:
file_reg = open('user.txt', 'a+')
file_reg.write(username)
file_reg.write(' ')
file_reg.write(password_first)
file_reg.write('\n')
break
else:
print("您输入的两次密码有误,请重新输入")
continue
print("注册成功,请记住您的账号和密码\n账号:{name}\n密码:{pwd}".format
(name=username,pwd=password_first))
04-24 05:24
查看更多