Sub topic 4
Handling the other case with else
This chapter assumes you can run Python scripts, write a basic if statement with a colon and an indented block, and use comparison operators such as >= and ==. You should also know that a condition evaluates to True or False. You will learn what else guarantees, how Python decides which if an else belongs to, and the mistakes that come from treating else as a catch-all.
What else does
An else clause attaches a block of code to an if statement. Python runs that block when the if condition is false. The else has no condition of its own.
age = 16
if age >= 18:
print('adult')
else:
print('minor')This prints minor. Python evaluates age >= 18 once. The result is False, so it skips the first block and runs the else block.
An if/else pair always runs exactly one of its two blocks, never both and never neither. That guarantee is the main reason to use else.
Syntax rules
The else keyword must follow these rules:
- It is written at the same indentation level as the
ifit belongs to. - It is followed directly by a colon, with no condition.
- It is followed by an indented block with at least one statement.
- It must come immediately after the
ifblock (or after the lastelifblock). Nothing else can sit between them at that indentation level.
The table shows the common ways to break these rules and what Python reports.
| Code | Problem | Result |
|---|---|---|
| `else:` with no `if` before it | `else` has nothing to attach to | `SyntaxError: invalid syntax` |
| `else x > 5:` | `else` takes no condition | `SyntaxError: expected ':'` |
| `else:` with no indented line after it | Empty block | `IndentationError: expected an indented block` |
| `else:` indented differently from its `if` | Python cannot pair them | `SyntaxError` or `IndentationError`, depending on the layout |
If you need a placeholder block while drafting, use pass.
logged_in = False
if logged_in:
print('welcome back')
else:
pass # TODO: show the login formelse is not the same as a second if
A common beginner mistake is to write two separate if statements where one if/else is needed. The two forms look similar, but they behave differently when the first block changes the data the second condition reads.
temperature = 30
if temperature > 25:
temperature = 20
print('cooling on')
if temperature <= 25:
print('heating on')This prints both cooling on and heating on. The first block lowers temperature to 20, and the second if is a new, independent test that reads the new value. Replace the second if with else and the bug disappears.
temperature = 30
if temperature > 25:
temperature = 20
print('cooling on')
else:
print('heating on')Now only cooling on prints. The else does not re-test anything. It runs because the original condition was false.
Using else also avoids repeating the opposite condition. Writing if x > 5: followed by if x <= 5: duplicates logic. If you later change one threshold and forget the other, a value can fall between the two tests and run neither block.
Which if does an else belong to?
Python uses indentation, not braces or keywords, to pair an else with an if. The else belongs to the nearest preceding if at the same indentation level.
is_member = True
balance = 0
if is_member:
if balance > 0:
print('discount applied')
else:
print('no balance')
else:
print('not a member')This prints no balance. The inner else lines up with the inner if balance > 0, so it handles the case where the member has no balance. The outer else lines up with if is_member, so it handles non-members. Moving the inner else left by four spaces would change its meaning.
is_member = True
balance = 0
if is_member:
if balance > 0:
print('discount applied')
else:
print('not a member')This version prints nothing. The else now pairs with the outer if. The member has a zero balance, so the inner if is false, and no else is attached to it. Nothing runs, and Python raises no error. When an else seems to run for the wrong case, check its indentation first.
else as a catch-all hides bad input
Because else has no condition, it runs for every value that fails the if test, including values you never intended. That makes it convenient but risky.
def door_action(command):
if command == 'open':
return 'opening'
else:
return 'closing'
print(door_action('open'))
print(door_action('opne'))
print(door_action(None))The output is opening, closing, closing. The typo 'opne' and the value None both fall into the else branch, and the door closes. The function treats "anything that is not open" as "close".
If only two inputs are valid, state both conditions and reject everything else. The elif clause, which the next chapter covers, makes this clean.
def door_action(command):
if command == 'open':
return 'opening'
elif command == 'close':
return 'closing'
else:
raise ValueError(f'unknown command: {command!r}')
print(door_action('close'))Here else is used for the case it is good at: anything unexpected. The decision rule is simple. Use a plain else when the two cases are complementary, such as age >= 18 versus not. Use an explicit test plus an error branch when the "other" case includes invalid input.
else after return, raise, or continue
When the if block ends with return, raise, break, or continue, the else is technically redundant. The code after the if only runs when the condition was false.
def sign(n):
if n < 0:
return 'negative'
else:
return 'non-negative'This function and the version without else behave identically. Many developers keep the else when both branches are equally important and the two cases are symmetric. They drop it when the if handles a special case and the rest of the function is the normal path. A later chapter on guard clauses covers that style. For now, know that both forms are correct and that style is the only difference.
Other places else appears
The keyword else also appears with for, while, and try. These are separate features with different meaning, so do not carry over the if intuition.
for n in [3, 5, 7]:
if n % 2 == 0:
print('found even', n)
break
else:
print('no even numbers')This prints no even numbers. In a loop, else runs when the loop finishes without hitting break. It does not mean "the condition was false". In a try statement, else runs when no exception was raised. This chapter is about if/else, but if you see an else with no if above it, check whether it belongs to a loop or a try.
Common errors
- Adding a condition to else. Write
elif x > 5:if you need a test. Plainelsenever takes one. - Mismatched indentation. An
elsethat is indented one level too far or too little silently pairs with a differentif, or fails to parse. - Using two
ifstatements for exclusive cases. If the first block can change the tested value, both blocks may run. - Putting statements between the
ifblock andelse. A line at theifindentation level ends the statement, and the followingelseis then aSyntaxError. - Trusting
elseto mean "valid but different". It also catches typos,None, and wrong types.
Exercise
The code below is meant to print exactly one message. What does it print for score = 55, and why? Then fix it so that it always prints exactly one message.
score = 55
if score >= 50:
print('pass')
score = score - 50
if score < 50:
print('fail')
Show answer
It prints both pass and fail. The first block subtracts 50, so score becomes 5. The second if is an independent test that reads the new value, and 5 < 50 is true. Replace the second if score < 50: with else:. Then the else block runs only when the original condition score >= 50 was false, so exactly one message prints (pass for 55).
Exercise
What does this code print, and which if does the else belong to?
x = 3
y = -1
if x > 0:
if y > 0:
print('both positive')
else:
print('x is not positive')
Show answer
It prints nothing. The else lines up with the outer if x > 0, so it runs only when x is not positive. Here x is 3, so the outer block runs. The inner if y > 0 is false, and it has no else, so no message is printed. Indenting the else to line up with if y > 0 would make the code print nothing different for x, but would cover the case "x positive, y not positive" and print x is not positive only if you also changed the message to match.