我正在尝试使用字典构建一个简单的登录和密码应用程序.它工作正常,除了检查登录是否与密码匹配的部分(在底部显示"登录成功!").
如果我要创建登录'a'和密码'b',然后创建登录'b'和密码'a',如果我尝试使用登录'a'和密码'a'登录,它会登录我.它只检查这些字符是否存在于字典中的某个位置,但如果它们是一对则不存在.
有任何建议如何解决这个问题?
users = {}
status = ""
while status != "q":
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "n": #create new login
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exist in the dictionary
print "Login name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
elif status == "y": #login the user
login = raw_input("Enter login name: ")
if login in users:
passw = raw_input("Enter password: ")
print
if login in users and passw in users: # login matches password
print "Login successful!\n"
else:
print
print("User doesn't exist!\n")
Run Code Online (Sandbox Code Playgroud)
编辑
现在,这是有效的,我试图将应用程序分为三个函数,以便于阅读.它有效,除了我得到无限循环.
有什么建议吗?
users = {}
status = ""
def displayMenu():
status = raw_input("Are you a registered user? y/n? Press q to quit: ")
if status == "y":
oldUser()
elif status == "n":
newUser()
def newUser():
createLogin = raw_input("Create login name: ")
if createLogin in users: # check if login name exists
print "\nLogin name already exist!\n"
else:
createPassw = raw_input("Create password: ")
users[createLogin] = createPassw # add login and password
print("\nUser created!\n")
def oldUser():
login = raw_input("Enter login name: ")
passw = raw_input("Enter password: ")
# check if user exists and login matches password
if login in users and users[login] == passw:
print "\nLogin successful!\n"
else:
print "\nUser doesn't exist or wrong password!\n"
while status != "q":
displayMenu()
Run Code Online (Sandbox Code Playgroud)
现在您正在检查给定的密码是否与中的任何键passw匹配(不正确)。您需要查看输入的密码是否与该特定用户的密码匹配。由于您已经检查过用户名是否存在于字典的键中,因此无需再次检查,因此请尝试以下操作:users
if passw == users[login]:
print "Login successful!\n"
Run Code Online (Sandbox Code Playgroud)
编辑:
对于您更新的代码,我将假设“无限循环”意味着您不能用来q退出程序。这是因为当您在里面时displayMenu,您将用户输入保存在名为 的本地变量status中。该局部变量并不引用status您正在检查的相同位置,
while status != "q":
Run Code Online (Sandbox Code Playgroud)
换句话说,您status在两个不同的作用域中使用变量(更改内部作用域不会更改外部作用域)。
有很多方法可以解决这个问题,其中之一就是改变,
while status != "q":
status = displayMenu()
Run Code Online (Sandbox Code Playgroud)
并在末尾添加一个 return 语句,displayMenu如下所示,
return status
Run Code Online (Sandbox Code Playgroud)
status通过这样做,您可以将脚本的本地范围的新值保存displayMenu到全局范围,以便while循环可以正常工作。
另一种方法是将此行添加到 的开头displayMenu,
global status
Run Code Online (Sandbox Code Playgroud)
这告诉 Python,statuswithindisplayMenu指的是全局作用域status变量,而不是新的局部作用域变量。
| 归档时间: |
|
| 查看次数: |
49838 次 |
| 最近记录: |