username=input("Enter username ")
password=input("Enter password ")
with open("myfile.txt", "r") as username_finder:
for lines in username_finder:
if line.startswith('Username: '):
if line.strip() == "Username: "+username and "Password: "+password:
print("Correct")
else:
print("Sorry, this username or password does not exist")
文件中的格式类似于`Username:john-password:psw123'
当我把多个用户放进文件中,然后尝试代码时,它说的是用户名和密码,由于某种原因,它是正确的和不正确的
首先,让我们分析代码的一部分。
您的命令中的条件
if line.strip() == "Username: "+username and "Password: "+password:
可以用括号(按运算符优先级(作为写入
(line.strip() == ("Username: " + username)) and ("Password: " + password)
现在,生成的and
操作的右侧操作符
("Password: " + password)
是一个非空字符串,因此被求值为True
(请参见布尔运算(,这使得if
语句与相同
if line.strip() == "Username: " + username
因此,密码永远不会被检查。
现在,转到程序的逻辑:
在您的输入文件中,您没有单词"Username:">和"Password: "
,而是
JohnDoe: pswd123
因此字符串文字"Username: "
和"Password: "
在if
语句中完全不合适。您希望将输入的用户名与文件中的用户名进行比较,并将输入密码与文件中的密码进行比较,在我们的示例中类似
if (username == "JohnDoe") and (password == "pswd123"):
或者-按照输入文件中的行格式-
if (username + ": " + password) == "JohnDoe: pswd123":
==
的右侧部分只是输入文件的行,因此if
语句可能看起来像
if (username + ": " + password) == line:
所以你的程序的(修正的(代码变成
username = input("Enter username: ")
password = input("Enter password: ")
with open("myfile.txt") as username_finder:
for line in username_finder:
if (username + ": " + password) == line.strip():
print("Correct")
break; # No need to search other lines
else:
print("Sorry, this username or password does not exist")
请注意for
循环的else
分支-它仅在循环自然耗尽而未被break
语句中断的情况下执行-请参阅文档中的for语句。
如果文件只包含用户名和密码,而不包含单词Username:
和Password
,则在相等性检查中不应包含这些字符串。应该是:
if line.strip() == username + ":" + password:
此外,您不应该打印在else
条件中找不到该名称。输入将只匹配文件中的一行,您将每隔一行打印一条错误消息。当您找到匹配项时,应该中断循环,并在for
循环的else:
类中打印错误消息。参见"搜索阵列报告";未找到";即使它';s找到
如果你想一直询问密码,直到它是正确的,把一切都放在一个循环中。
check_failed = True
while check_failed:
username = input("Enter username: ")
password = input("Enter password: ")
with open("myfile.txt") as username_finder:
for line in username_finder:
if (username + ": " + password) == line.strip():
print("Correct")
check_failed = False
break;
else:
print("Sorry, this username or password does not exist")