This is a pretty common problem for people to run into: what does it mean when my function has multiple return points?
Setting aside the debate over whether or not multiple returns should ever happen, the fact is that they do. The important thing to remember is this:
A function is finished as soon as it returns.
In every modern programming language I'm familiar with, as soon as a function hits a return point, it quits processing*. If there's a return value, that gets passed back to wherever the function was originally called. Python is no exception.
Your function has a little extra junk in there to make it harder to read, which isn't helping. Specifically, the assignment to b
is totally superfluous, because the assigned value is never used. We can rewrite your function like this for clarity, while still explaining multiple returns:
def proc4(a, b): # line 1
if test(a): # line 2
return b # line 3
return a # line 4
Now what happens is this. Say that test(a)
evaluates to True
on line 2. We enter the if
block, and encounter line 3: return b
. The function now returns the value of b
to wherever it was called from, and execution is finished. Line 4 is never executed.
Alternately, if test(a)
evaluated to False
, then we don't enter the if
block. In this case, we skip over line 3, straight to line 4. Now, we execute line 4, and return the value of a
to wherever proc4
was called.
*There are certain flow-control statements, such as finally
in many languages, that can cause code in a function to be executed after a return statement is encountered. For simplicity and because it's off-topic, I'm not going to go into that in this answer. Thanks to @Racso for pointing out that I missed this!