Sub topic 4
Handling the other case with else
This chapter assumes you can run Python scripts, know the basic types (int, str, bool, list, dict, None), and have written a simple if statement. Here you will learn how else works, what it guarantees, and the errors that come up most often.
What else does
An else clause attaches to an if statement. It holds the code that runs when the if condition is not true. Python runs exactly one of the two blocks, never both and never neither.
age = 20
if age >= 18:
print('adult')
else:
print('minor')Here age >= 18 is True, so Python prints adult and skips the else block. If you change age to 15, the condition is False and Python prints minor.
The working model
Python evaluates the if condition once. If the result is truthy, it runs the if block and jumps past the else block. If the result is falsy, it jumps straight to the else block. The else clause has no condition of its own. It means "everything the if did not catch."
Syntax rules
elsemust line up with theifit belongs to, at the same indentation level.elseis followed by a colon and has no condition.- The
elsebody must be indented and contain at least one statement. - Only one
elseis allowed perifstatement, and it must come last.
Common errors
The most frequent mistake is giving else a condition.
score = 40
if score >= 50:
print('pass')
else score < 50:
print('fail')This raises a SyntaxError. If you need a second condition, use elif, which the next chapter covers. If you do not, drop the condition, because else already means "not the above."
Another mistake is indentation that detaches the else from its if. In the example below, the else lines up with the inner if, so it belongs to that one instead.
logged_in = True
is_admin = False
if logged_in:
if is_admin:
print('admin panel')
else:
print('please log in')In this version else is aligned with the outer if, so it runs only when logged_in is false. A signed-in user who is not an admin sees nothing. Check alignment whenever you nest if statements.
When else is not needed
If the if block ends with return, raise, break, or continue, the else is often redundant, because the code after the if only runs when the condition was false.
def classify(n):
if n < 0:
return 'negative'
return 'non-negative'
print(classify(-3))
print(classify(8))This returns the same results as an if/else version. Both are correct. Use else when the two branches are equally important and read as a pair. Drop it when the first branch is an early exit.
Using else for defaults
else works well for assigning a value that depends on a condition.
temperature = 31
if temperature > 30:
advice = 'wear a hat'
else:
advice = 'no hat needed'
print(advice)Both branches assign advice, so the variable is always defined afterward. If you assigned it only inside an if with no else, a false condition would leave it undefined and a later print(advice) would raise a NameError.
Exercise
What does this code print, and why? n = 5, then if n > 10: print 'big', else: print 'small'. Then, on a new line outside the block, print('done').
Show answer
It prints small and then done. The condition n > 10 is False, so the else block runs. The final print is not indented, so it is outside the if/else and always runs.
Exercise
Why does else score < 50: fail, and how do you fix it?
Show answer
else cannot take a condition, so Python raises a SyntaxError. Remove the condition and write else:, or change it to elif score < 50: if you need to test a second condition.