我正在创建一个以登录功能开始的游戏
用户可以“登录(A)或创建帐户(B)”
我的问题是,如果用户使用一个不存在的用户名登录,我会得到一个KeyError:“(无论他们键入什么用户名)”
预期结果: 如果发生这种情况,我希望代码输出“用户不存在”
这个问题可以通过以下代码重现:键入“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()
额外信息:有关登录功能如何工作的更多上下文。
出现错误是因为您试图使用字典中不存在的密钥访问
users
字典。您使用的密钥是用户的用户名。因此,当字典中没有具有该用户名的用户时,您将收到KeyError
使用
try
和except
的替代方法是将您的字典重组为一个用户字典数组,每个用户字典包含键username
和password
改头换面
研究如何使用python的
try
和except
。它们的存在是为了帮助我们在自定义处理错误的方式时处理错误。因此,对于您的具体问题,请尝试一下:相关问题 更多 >
编程相关推荐