为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森栏 2023-08-22 15:31:44
我正在创建一个以登录功能开始的游戏用户可以“登录 (A) 或创建帐户(B)”我的问题是,如果用户使用不存在的用户名登录,我会收到 KeyError:“(无论他们输入什么用户名)”预期结果: 如果发生这种情况,我希望代码输出“用户不存在”。可以使用此代码重现该问题,然后输入“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条经验 获得超13个赞

通过改变修复


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 关注
  • 1552 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信