views:

86

answers:

4

Hello all,

I have the following code:

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    for x in geodatabaseList:
        if x == self.outputGeodatabase:
            return True
        else:
            pass
    return False

What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    for x in geodatabaseList:
        if x == self.outputGeodatabase:
            return True
            break
        else:
            pass
    return False

If the following code does not solve my problem, what can i use to do simulate that behavior?

Thanks

+1  A: 

The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.

Here is a simple test which you could run to prove the point:

def someFunction(nums):
    for i in nums:
        if i == 1:
            return "Found 1!"
    return "Never found 1"

And running it:

>>> someFunction([2])  
'Never found 1'  
>>> someFunction([2,1,3])  
'Found 1!'
matt b
great, as well. thanks for the simplicty of the test!
George
+8  A: 

return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as

def testGeodatabase(self):
    return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")
Jonathan Feinberg
thank you very much. Very pythonic :PIn this case, if the self.outputGeodatabase does not exist in the list, will that cause the function to return None or False? My bet is None...
George
No need to risk your money... try it! `print 'a' in ('b','c')`
Jonathan Feinberg
http://docs.python.org/reference/expressions.html#in scroll down to "The operators in and not in test for collection membership."
matt b
Thanks, very cool!
George
+2  A: 

You don't need the break keyword in the code above. Actually, you don't need the

else:
   pass

either. The

return True

will exit the function.

Jordan
A: 

I think that using any() is the best choice:

def testGeodatabase(self):
    geodatabaseList = self.gp.ListWorkspaces("*","ALL")
    return any(x == self.outputGeodatabase for x in geodatabaseList)
hughdbrown