The Python Oracle

A statement that has the same indentation with its previous "if" statement will always be executed?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Book End

--

Chapters
00:00 A Statement That Has The Same Indentation With Its Previous &Quot;If&Quot; Statement Will Always Be
01:03 Answer 1 Score 2
01:28 Accepted Answer Score 3
02:48 Thank you

--

Full question
https://stackoverflow.com/questions/4713...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 3


This is a great question you have asked, and it's an issue a lot of new people have with functions specifically.

The issue lies with the return keyword. In a function, when it returns a value, the function immediately breaks. Thus, no subsequent code in the function is run. Because of this, we can short-hand our conditional statements to:

if a > b:
    return a
    # Function breaks here - no more code is executed.
# This bit is never reached if a is returned
return b

Observe:

def test():
    if 10 > 5:
        print("Hello!")
        return True
    print("Hi!")
    return False

When we call test(), only Hello! is printed.


One reason this is helpful is to stop erroneous whitespace when having multiple conditional statements in Python. Of course, in most other programming languages, since whitespace isn't a feature, it's not as necessary.

Imagine you were writing a function to check if a number was prime, where lots of conditional statements were required. (Of course, for the sake of this example, this isn't efficient):

def is_prime(n):
    if n == 1:
        return False
    else:
        if n == 2:
            return True
        else:
            for i in range(2, n):
                if n % i == 0:
                    return False # A factor exists
                else:
                    continue
            return True

Knowing that a return breaks the function, we can re-write this as:

def is_prime(n):
    if n == 1:
        return False
    if n == 2:
        return True:
    for i in range(2, n):
        if n % i == 0:
            return False # A factor exists
    return True

See how the indentation is so much cleaner?




ANSWER 2

Score 2


That's because you can't return twice from a function. When if is satisfied, it will return and won't execute any more statement. So, the next return statement is unreachable.

The next return will only execute when if is failed. else is also executed when if is failed.

That's why your teacher says, both of them are same.