简体   繁体   English

不了解for循环中的if / else行为

[英]Don't understand if/else behavior within for loop

So I have a object with a method that is supposed to iterate over a list which is defined in the class. 所以我有一个带有方法的对象,该方法应该遍历类中定义的列表。

When I use a simple if statement, I get the expected result, however, when I add an else statement I get strange results. 当我使用一个简单的if语句时,我得到了预期的结果,但是,当我添加一个else语句时,我得到了奇怪的结果。

Class SomeClass(object):
     def __init__(self):
          self.config = ['something', 'this exists', 'some more stuff']

     def check_this(self):
          for line in self.config:
               if "this exists" in line:
                    return True

The above code returns True as soon as I get to the 2nd element in the list. 一旦我到达列表中的第二个元素,上面的代码将返回True。

If I change the code to the following. 如果我将代码更改为以下内容。 The method returns False. 该方法返回False。

Class SomeClass(object):
     def __init__(self):
          self.config = ['something', 'this exists', 'some more stuff']

     def check_this(self):
          for line in self.config:
               if "this exists" in line:
                    return True
               else:
                    return False

I have to be missing something here. 我必须在这里丢失一些东西。 Python 2.7.6 on MAC OS X MAC OS X上的Python 2.7.6

In your latter case you never hit the 2nd element, because the 1st returns False . 在后一种情况下,您永远不会点击第二个元素,因为第一个元素返回False A function can only return one time. 一个函数只能return一次。

In your first method, the only time it will return is if it get into your if block and will return True . 在您的第一个方法中,它将返回的唯一时间是它是否进入了if块并返回True If it never gets into the if block, it will return None . 如果它永远不会进入if块,它将返回None

In your second method, in the very first iteration, 'this exists' is not in line so it returns False and stops iterating. 在您的第二种方法中,在第一次迭代中, 'this exists'不在line因此它返回False并停止迭代。

If I understand the intention of that function, it could simply be 如果我了解该功能的意图,可能只是

def check_this(self):
    return "this exists" in self.config

I think this is what you want: 我认为这是您想要的:

 Class SomeClass(object):
      def __init__(self):
           self.config = ['something', 'this exists', 'some more stuff']

      def check_this(self):
          if "this exists" in self.config:
              return True
          else:
              return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM