def login(): i = 1 while i <= 3: username = input("输入用户名:") password = input("输入密码:") with open("a.txt") as f: for line in f.readlines(): user = line.strip().split() if user[0] == username and user[1] == password: print("登录成功!") return print("用户名或密码错误!") i += 1 print("账号锁定!") login()代码优化
时间: 2024-02-14 20:24:01 浏览: 67
可以将文件读取和用户验证分开处理,将用户验证的部分封装成一个函数,并添加参数来传递用户名和密码。同时,可以将错误提示信息统一处理,并在登录失败时增加一定时间的等待,以防止暴力破解。下面是代码优化后的示例:
```
import time
def read_user_info():
with open("a.txt") as f:
users = [line.strip().split() for line in f.readlines()]
return users
def validate_user(users, username, password):
for user in users:
if user[0] == username and user[1] == password:
return True
return False
def login():
i = 1
users = read_user_info()
while i <= 3:
username = input("输入用户名:")
password = input("输入密码:")
if validate_user(users, username, password):
print("登录成功!")
return
else:
print("用户名或密码错误!")
if i < 3:
print("请稍等片刻再尝试。")
time.sleep(1)
i += 1
print("账号锁定!")
login()
```
阅读全文