我正在尝试将一种登录系统编程为我的计算过程的一部分。编程时我遇到的问题是,当我输入用户名为" j.smith"它再次要求用户名。我认为它应该直接跳到密码检查。任何建议或错误通知都非常感谢。 谢谢!
#SETTING VARIABLES
user_name = "l.parker"
password = "Password1"
user_name_2 = "j.smith"
password2 = "Password2"
user = "user0"
#USERNAME CHECK
if input("What is your username?") == user_name:
print("Hello Luke")
user == "user1"
elif input("What is your username?") == user_name_2:
print("Hello John")
user == "user2"
else:
print("That's not right")
quit()
#PASSWORD CHECK
if user == "user1":
if input("What is your password?") == password:
print("You have successfully logged in")
else:
print("That's not right")
quit()
elif user == "user2":
if input("What is your password?") == password2:
print("You have successfully logged in")
else:
print("That's not right")
quit()
答案 0 :(得分:1)
您在一行中合并两件事:获取用户输入并检查其是否与用户名匹配。这使得很难检查多个用户名。要解决这个问题,可以通过将用户输入放入变量并对其进行检查来拆分它。
name = input("What is your username?")
if name == user_name_1:
print("Hello Luke")
user = "user1"
elif name == user_name_2:
print("Hello John")
user = "user2"
答案 1 :(得分:1)
虽然这个答案在这里有效地重复了其他答案,但我觉得其中任何一个都没有向你解释为什么你的代码的行为方式就是这样。
让我们来看看这段代码:
if input("What is your username?") == user_name:
print("Hello Luke")
user == "user1"
elif input("What is your username?") == user_name_2:
print("Hello John")
user == "user2"
else:
print("That's not right")
quit()
第一行有什么作用?
if input("What is your username?") == user_name:
如果将用户输入的结果与变量user_name
的内容进行比较。
执行如下:
input()
电话返回,并与user_name
所以它进入下一个条件:
elif input("What is your username?") == user_name_2:
同样,发生了与之前相同的事件序列,其中包括再次提示用户输入用户名。
这就是你看到提示两次的原因,因为你已经要求Python一遍又一遍地提示用户检查你检查的每个条件,直到找到匹配为止。
解决方案(正如已经回答过的其他人所指出的那样)只是问一次问题,存储它,然后进行比较。请参阅popovitsj的答案。
虽然可能很容易使用Vyktor的答案,但我会提醒您不要复制/粘贴大量的stackoverflow代码并在分配中使用它们。这可能会让你陷入困境(辅导员/讲师不是白痴 - 我是从导师的经验中说话)而且只需要5秒的谷歌搜索来证明学生盲目地从stackoverflow完全重写他们的代码。
答案 2 :(得分:0)
您意外地使用比较运算符(==
)而不是在此行上分配运算符(=
):
user == "user1"
# Should be:
user = "user1"
另外,您多次调用输入(已pointed out by popovitsj)。
但更具可扩展性的解决方案是将用户封装到对象中并将多个用户存储在列表中,例如:
class User(object):
def __init__(self, username, password, common_name=None):
self.username = username
self.password = password
self.common_name = common_name
users = [
User('l.parker', 'Password1', 'Luke'),
User('j.smith', 'Password2', 'John')
]
name = input('What is your username? ')
# Fetch user
user = None
for u in users:
if u.username == name:
user = u
break
# Any user matched?
if user is None:
print('That\'s not right')
quit()
password = input('What is your password? ')
# Password
if user.password != password
print('That\'s not right')
quit()
print('Dear {}, you have successfully logged in!'.format(user.common_name))