嗨,我是一名大学学生,这是我第一次选修编程科目。我正在努力创建一个简单的登录程序,它接受两个输入并检查是否有成功的登录组合。
这是我到目前为止得到的代码。。。提前感谢您的帮助!
#Inputs username and password
#If the inputs match the accounts
#Outputs "welcome back <username>"
#If the inputs dont match the accounts
#Output "Wrong username or password"
#Initialising variables
use1 = "alice"
use2 = "bob"
use3 = "carol"
ans1 = "greenfingers"
ans2 = "builder"
ans3 = "danvers"
login1 = input("Username: ")
login2 = input("Password: ")
if (login1 == use1 or use2 or use3):
if (login2 == ans1 or ans2 or ans3):
print("Welcome back {}".format(login1))
else:
print("Wrong username or password")
您不能以这种方式使用or
,您需要编写一个条件
if (login1 == use1 or login1 == use2 or login1 == use3):
if (login2 == ans1 or login2 == ans2 or login2 == ans3):
print("Welcome back {}".format(login1))
else:
print("Wrong username or password")
最好使用字典来简化检查条件并获得更好的查找性能:
user_passwords = {
'alice': 'greenfingers',
'bob': 'builder',
'carol': 'danvers',
}
login = input("Username: ")
password = input("Password: ")
if login in user_passwords and user_passwords[login] == password:
print(f'Welcome back {login}')
else:
print("Wrong username or password")
对于python格式字符串=链接
,您可以使用'in'而不是'或'
use1 = "alice"
use2 = "bob"
use3 = "carol"
ans1 = "greenfingers"
ans2 = "builder"
ans3 = "danvers"
login1 = input("Username: ")
login2 = input("Password: ")
if ((login1 in [use1,use2, use3 ]) and (login2 in [ans1,ans2, ans3 ])):
print(f"Welcome back {login1}")
else:
print("Wrong username or password")