3 回答

TA貢獻1864條經驗 獲得超2個贊
您收到錯誤是因為您嘗試使用users
字典中沒有的鍵訪問字典。您使用的密鑰是用戶的用戶名。因此,當字典中沒有具有該用戶名的用戶時,您會收到KeyError
使用try
and的另一種方法except
是將字典重組為用戶字典數組,每個用戶字典包含鍵username
和password

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()

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")
添加回答
舉報