Sean
Sean

Reputation: 545

Python: Why else statement can be discarded in this simple expression?

I apologize for how obvious this answer must be, but I just can't seem to find out why an else statement isn't needed in the following function which returns True -

def boolean():
    x = 1
    if x == 1:
        return True
    return False

boolean()

My beginner coding mind is confused why False isn't being returned. The if statement returns True, then outside of that if statement, False is returned. I would've thought to write -

def boolean():
    x = 1
    if x == 1:
        return True
    else: 
        return False

boolean()

Why isn't the else statement needed here? Thank you very much for enlightening me on this.

Upvotes: 2

Views: 102

Answers (1)

Robo Jeeves
Robo Jeeves

Reputation: 76

The execution of a function always ends as soon as a return statement is run. Nothing past that point is even evaluated. For example, if you added a print statement immediately after the return statement, you would not see it printed in the console.

Similarly, the execution of this function never reaches return False because True was already returned.

Upvotes: 5

Related Questions