亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當用戶名不存在時,登錄功能會創建 KeyError - Python

當用戶名不存在時,登錄功能會創建 KeyError - Python

森欄 2023-08-22 15:31:44
我正在創建一個以登錄功能開始的游戲用戶可以“登錄 (A) 或創建帳戶(B)”我的問題是,如果用戶使用不存在的用戶名登錄,我會收到 KeyError:“(無論他們輸入什么用戶名)”預期結果: 如果發生這種情況,我希望代碼輸出“用戶不存在”??梢允褂么舜a重現該問題,然后輸入“A”登錄并輸入不存在的隨機用戶名。users = {} # Currently empty list called Users. Stores all log insglobal statusstatus = ""def LogIn():#Function is called Log In. Can be called at any time.    status = input("Log in (A) or Create an account(B) - Enter 'A' or 'B' ")   # asks for log in information    status = status.upper()    if status == "A":        oldUser() #Already has an account    elif status == "B":        newUser() #Would like to make a new account        return status #Moves on to the function named statusdef newUser(): # Creating an account.    CreateUsername = input("Create username: ") #Enter a what your username is    if CreateUsername in users: # check if login name exists in the list        print ("\n Username already exists!\n")    else:        createPassw = input("Create password: ")        users[CreateUsername] = createPassw # add login and password        print("\nUser created!\n")     def oldUser():    username = input("Enter username: ")    passw = input("Enter password: ")    # check if user exists and login matches password    if passw == users[username]:      print ("Login successful!\n")      print('Game begins')    else:        print ("\nUser doesn't exist or wrong password!\n")while status != "q":                status = LogIn()額外信息:有關登錄功能如何工作的更多背景信息。
查看完整描述

3 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

您收到錯誤是因為您嘗試使用users字典中沒有的鍵訪問字典。您使用的密鑰是用戶的用戶名。因此,當字典中沒有具有該用戶名的用戶時,您會收到KeyError

使用tryand的另一種方法except是將字典重組為用戶字典數組,每個用戶字典包含鍵usernamepassword


查看完整回答
反對 回復 2023-08-22
?
翻翻過去那場雪

TA貢獻2065條經驗 獲得超14個贊

通過改變修復


def oldUser():

    username = input("Enter username: ")

    passw = input("Enter password: ")


    # check if user exists and login matches password

    if username not in users:

      print ("Username doesn't exist")

      print('Game begins')

    elif passw == users[username]:

        print('Log In successful')

    else:

        print ("\nUser doesn't exist or wrong password!\n")


while status != "q":            

    status = LogIn()


查看完整回答
反對 回復 2023-08-22
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

考慮使用 pythontry和except. 它們的存在是為了幫助我們在出現錯誤時處理錯誤,同時自定義處理這些錯誤的方式。因此,對于您的具體問題,請嘗試一下:


def oldUser():

   username = input("Enter username: ")

   passw = input("Enter password: ")


# check if user exists and login matches password

   try:

     if passw == users[username]:

        print ("Login successful!\n")

        print('Game begins')

   except:

      print ("\nUser doesn't exist or wrong password!\n")


查看完整回答
反對 回復 2023-08-22
  • 3 回答
  • 0 關注
  • 1681 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號