jeudi 14 juillet 2016

Return statements acting weird in "if" statements in Python

My question is regarding this statement I read online that went something along the lines of "lines that follow the 'if statement' and are at the same indentation as the "if statement" will always run, regardless whether the 'if statement' is true or false." I'll show that using my examples below.

So I have this procedure that takes in two numbers as inputs and returns the greater of the two inputs.

Therefore, the 4th and 5th lines of code in this first example, which are at the same level of indentation as "if a>b:" should always run according to the statement above.

Example #1

def bigger(a,b):
    if a>b:
        x = "the first number is bigger"
    x = "the second number is bigger"
    return x
print bigger(9,7)

Python prints "the second number is bigger," so the code is working according to that original statement I wrote in the beginning. Even though that is false because 9>7.

But where I run into confusion is when return statements are used in the following example:

Example #2

def bigger(a,b):
    if a>b:
        return "the first number is bigger"
    return "the second number is bigger"
print bigger(9,7)

This time, Python prints "the first number is bigger." This is true because 9>7

My confusion: Shouldn't the 4th line of code in this second example, "return "the second number is bigger"", always run because it's at the same indentation level of the "if statement," just like we saw in example #1?

It seems like the two examples of code contradict each other because in the example #1, Python recognizes the "second number is bigger" line and prints that line but in example #2, Python ignores the "second number is bigger" line and prints the other "first number is bigger" line.

I tried to make this as clear as possible. Thanks

Aucun commentaire:

Enregistrer un commentaire