当用户名不存在时,登录功能会创建 KeyError - Python

我正在创建一个以登录功能开始的游戏

用户可以“登录 (A) 或创建帐户(B)”

我的问题是,如果用户使用不存在的用户名登录,我会收到 KeyError:“(无论他们输入什么用户名)”

https://img4.mukewang.com/64e464a600019f4005440145.jpg

预期结果: 如果发生这种情况,我希望代码输出“用户不存在”。


可以使用此代码重现该问题,然后输入“A”登录并输入不存在的随机用户名。


users = {} # Currently empty list called Users. Stores all log ins

global status

status = ""


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 status


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

额外信息:有关登录功能如何工作的更多背景信息。

https://img4.mukewang.com/64e464b600010e3604040232.jpg

森栏
浏览 1630回答 3
3回答

慕斯王

您收到错误是因为您尝试使用users字典中没有的键访问字典。您使用的密钥是用户的用户名。因此,当字典中没有具有该用户名的用户时,您会收到KeyError使用tryand的另一种方法except是将字典重组为用户字典数组,每个用户字典包含键username和password

翻翻过去那场雪

通过改变修复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()

斯蒂芬大帝

考虑使用 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")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python