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

2024-04-26 18:56:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

Full Error shown

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

这个问题可以通过以下代码重现:键入“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()

额外信息:有关登录功能如何工作的更多上下文。 More Context


Tags: or用户ininputifdefstatususername
3条回答

出现错误是因为您试图使用字典中不存在的密钥访问users字典。您使用的密钥是用户的用户名。因此,当字典中没有具有该用户名的用户时,您将收到KeyError

使用tryexcept的替代方法是将您的字典重组为一个用户字典数组,每个用户字典包含键usernamepassword

改头换面

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

研究如何使用python的tryexcept。它们的存在是为了帮助我们在自定义处理错误的方式时处理错误。因此,对于您的具体问题,请尝试一下:

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

相关问题 更多 >