2

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.

handras
  • 1,548
  • 14
  • 28
Sean
  • 515
  • 7
  • 17
  • 2
    "The if statement returns True, then outside of that if statement, False is returned", how can two values be returned from a function? And why not just `return x == 1`? – Sean Pianka Nov 26 '18 at 18:44
  • For some reason, I wasn't sure that only one value can be returned from a function. And `return x == 1` would be a better way of writing that, instead of an if statement which isn't needed. Thank you for pointing that out. – Sean Nov 26 '18 at 18:50

1 Answers1

5

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.