Python之簡單的用戶名密碼驗證

題目要求:python

輸入用戶名密碼
認證成功後顯示歡迎信息
輸錯三次後鎖定
 
#要求使用文件存儲用戶名和密碼,每次從文件讀入用戶名和密碼用來驗證,若是輸錯三次密碼該帳戶會被鎖定,並講鎖定的用戶名寫入文件
#帳號密碼正確輸出歡迎信息
 
涉及知識點:
文件讀寫操做
循環流程
程序判斷流程
通過分析構思
我寫的初版代碼以下:
#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()
相關文章
相關標籤/搜索