首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的输出只显示错误,即使它是正确的

我的输出只显示错误,即使它是正确的
EN

Stack Overflow用户
提问于 2018-06-11 01:28:33
回答 1查看 35关注 0票数 -1

我不明白为什么它只显示错误,当它在脚本中使用用户名和密码时,它只显示它工作的最后一行?

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 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来创建用户名-密码对。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50786291

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档