Ricardo Pomalaza
Ricardo Pomalaza

Reputation: 27

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

Upvotes: 1

Views: 98

Answers (3)

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

If n1 > n2 evaluates to true, it will execute the first return statement - since it is inside the if block, and immediately exit the function, and there is even no chance to reach the second return statement at all.

On the other hand, if n1 > n2 evaluates to false, the first return statement is skipped, and now it reaches the second return statement and executes it.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798516

return terminates execution of the function unilaterally. The code never has a chance to get to the second return if the first executes.

Upvotes: 3

BrenBarn
BrenBarn

Reputation: 251355

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.

Upvotes: 4

Related Questions