vendredi 26 juin 2015

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.

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.

If I change the code to the following. The method returns 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

Aucun commentaire:

Enregistrer un commentaire