題目要求:
輸入用戶名密碼
認證成功后顯示歡迎信息
輸錯三次后鎖定
#要求使用文件存儲用戶名和密碼,每次從文件讀入用戶名和密碼用來驗證,如果輸錯三次密碼該賬戶會被鎖定,並講鎖定的用戶名寫入文件
#賬號密碼正確輸出歡迎信息
涉及知識點:
文件讀寫操作
循環流程
程序判斷流程
經過分析構思
我寫的第一版代碼如下:
#Author jack
# _*_ coding: utf-8 _*_
#date 2019-08-14
'''
作業一:編寫登錄接口
輸入用戶名密碼
認證成功后顯示歡迎信息
輸錯三次后鎖定
'''
#判斷用戶賬號密碼
def check_pass(username, password):
with open('userfile.txt', 'r+') as f:
content = f.readlines()
for i in content:
if i.split(',')[0] == username and i.split(',')[1].strip('\n') == password:
return True
break
else:
return False
#判斷用戶名是否鎖定:
def isLock(username):
with open('locklist.txt', 'r') as f:
cont = f.read()
if username in cont:
return False
else:
return True
#寫鎖定用戶名到locklist,如果用戶輸錯三次,就調用此函數,講鎖定的用戶名寫入此文件
def writeErrlist(username):
with open('locklist.txt', 'a+') as f:
f.write(username)
f.write('\n')
def main():
count = 0 #存儲輸密碼次數
while count < 3:
username = input('Please input your username: ')
is_lock = isLock(username)
if is_lock:
passwd = input('Please input your password: ')
result = check_pass(username, passwd)
if result:
print('welcome back! "{}"'.format(username))
break
else:
count += 1
if count < 3:
print('Invalid username or password, Please try again!')
else:
print('Too many attempts, Your account has benn locked.')
writeErrlist(username)
else:
print('Your account has been locked!!!')
if __name__ == "__main__":
main()
