What's the point of else statement?

I have a question regarding my correct solution to Question #1 of Python Code Challenges: Control Flow, link below …
(Advanced) https://www.codecademy.com/courses/learn-python-3/articles/advanced-python-code-challenges-control-flow

My solution (first one below) was a correct option that produced the correct output. But it is different from the solution suggested by Codecademy (second one below) …

def in_range(num, lower, upper):
if num >= lower and num <= upper:
return True
else:
return False

def in_range(num, lower, upper):
if(num >= lower and num <= upper):
return True
return False

Is the second code above as suggested by Codecademy preferred and more correct strictly because it has less lines? Then why is the else statement ever necessary?

else is important when return is not used. It sets out an alternate or default action.

a = 42
if a % 6 and a % 7:
    print ('Not divisible by 6 and 7')
else:
    print ('Divisible by 6 and 7')

    
Divisible by 6 and 7

When return is applied, there is no need for the else branch since flow will have ended when the if condition is met. If not, flow will continue to the next line, the other return.

In truth, the above can all be written in one return statement:

def in_range(num, lower, upper):
    return lower <= num <= upper
1 Like

If a return is hit then that result is returned and nothing else is processed. In the Codecademy solution return False is basically the default behaviour, and True only gets returned if the return in the if statement happens to be called.

Consider an if statement without returns:

a = 1
b = 1

if a == b:
   print("These match!")

print("These don't match!")

These match!
These don't match!

Your output will always include “These don’t match!” because it sits outside of the if statement, to ensure that this works correctly you would need to have an else in there instead

1 Like

Thanks for your response! Two questions:

So then, in following with the second code solution that was suggested by Codecademy where the else statement was omitted and replaced simply with … return False … why not just do the same in your example …

a = 42
if a % 6 and a % 7:
print (‘Not divisible by 6 and 7’)
print (‘Divisible by 6 and 7’)

I am guessing it has something to do with the last print statement being in global realm (is that the correct term)? As in the last print statement will always be printed because it is outside of the function.

Second question, there’s that thing again in your elegant code where it’s assumed that the return statement will yield a True or False statement instead of another type of value. How does that work?

1 Like

Because we don’t want the possibility for both print statements, only one in each case. The flow still comes to the last line. else is only read when the if is falsy. The example is not a function, just inline code.

It works as a comparison, which is boolean. A bool can only be one of, True or, False.

1 Like