Search code examples
pythonfunctionprocedures

Why does this Python code work as it does? Please explain


In the CS101 course at Udacity, the trainer demonstrates procedures in Python by writing the following code to print out the bigger number of the two parameters n1 & n2

def bigger(n1,n2):
    if n1 > n2:
      return n1
    return n2

So, for example, he does

print bigger(6,3)

And the code runs and prints out:

6

That's fine. My question is this:

Since he clearly states in the course that "return n2" at the end of the code will always execute whether or not the if statement is true or false, why is return not always n2? Why does it return n1 even when 'return n2' is outside of the if-statement? It should execute regardless of whether the IF-statement is true or not. So I'm confused. O.o


Solution

  • It is not true that return n2 will always execute. If n1 is greater than n2, the first return n1 will execute. That returns from the function, and nothing else in the function is executed. A function can only return once.