I'm in the process of learning python, and I can't wrap my head around a piece of code in the book:
def find_value(List, value):
for i in range(len(List)):
if List[i] == value:
return i
return -1
I've tried running the code, and it returns the index if the value is in it, and returns -1 if it isn't, but what I don't understand is since the 'return -1' is outside the for loop, and if statement, should it not be run every time the code is executed? Or does return only get processed once, the first time it is called?
I just want to make sure I understand this concept before moving on. Thanks in advance
No, you can have as many return
statements in as many places as you like:
def function():
... # do something
return 1
return
return [3, 4, 5]
return next(__import__('os').walk('.'))[-1:-1000000000:-1]
Though the important thing to keep in mind that only the first return
that your function encounters will count, and anything else that would've succeeded it is not touched.
In the function above, you'll get 1
as the result and nothing else.
This sort of "flow of control" is why you can even do weird stuff like this -
def foo():
return True
whatIsThisIdontEven__somethingWeird.jpg # would ordinarily throw RuntimeErrors anywhere else
print(foo())
# True
In your case, it entirely depends on your code flow at runtime, but you'll still end up encountering only one return
, and consequently returning only once.
Note that one difference is in the case of try-except-finally, where the return
in the final
clause always wins.
def function():
try:
... # do something
return 1
except SomeException:
... # do something else
finally:
return 2
In the case of normal execution, you'll encounter return 1
in try
, but because of the semantics of the finally
clause, you'd still end up returning 2. I believe this is the only exception.
Now, yield
, on the other hand, is a different matter...