我不明白为什么它只显示错误,当它在脚本中使用用户名和密码时,它只显示它工作的最后一行?
def login():
for username in range(3):
username = input("Enter your username:")
password = input("Enter your password:")
d="example1"
k="example2"
s="school"
f=open("bob.txt")
lines=f.readlines()
if username == lines[0] and password == lines[1]:
print("welcome to soar valley",d)
break
if username == lines[2] and password ==lines[3]:
print("welcome to soar valley",s)
break
if username == lines[4] and password ==lines[5]:
print("welcome to soar valley",k)
break
if username or password != lines[0] or lines[1] or lines[2]or lines[3]or
lines[4] or lines[5]:
print("wrong try again")
login()发布于 2018-06-11 02:07:25
您误用了操作符or。
if username or password != lines[0] or lines[1] or lines[2]or lines[3]or lines[4] or lines[5]:
这一行的执行与您预期的不同。
In the Python 3.7 documentation of or,
以下值被解释为false: False、None、所有类型的数字零以及空字符串和容器(包括字符串、元组、列表、字典、集合和冻结集)。所有其他值都被解释为true。
因此,非空字符串总是被解释为True,这意味着您的目标行可以在假设的条件下简化(用户名和密码不为空,文件bob.txt开头至少包含6行非空行):
if True or True != True or True or True or True or True or True:
这一切都是真的。而这正是你意想不到的。
根据您的情况,您可以尝试使用关键字not in
if username not in lines[0:5] and password not in lines[0:5]:
最好使用dict来创建用户名-密码对。
https://stackoverflow.com/questions/50786291
复制相似问题