我正在创建一个以登录功能开始的游戏
用户可以“登录 (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()
额外信息:有关登录功能如何工作的更多背景信息。
慕斯王
翻翻过去那场雪
斯蒂芬大帝
相关分类