else
else is the path Python takes when the if condition (and every elif) is not met.
Used in 109 lessons of the course, from 00.02.
else goes after an if (and its elif branches, if any). It has no condition: it means "in every other case".
Python checks conditions from top to bottom. It runs the first block whose test is true. If none is, it runs the else block. Two branches never both run.
You write it with a colon and an indented block, lined up with the if:
if x > 0:
print("positive")
else:
print("not positive")
In the course you see it in lesson 00.02: if the Python version is new enough, a success message prints; in the else, the ❌ "Python is too old" message prints. Every case gets a clear answer, so you are never left without a message.
Reach for it when: you have two paths and want one of them to cover everything the `if` did not.
Examples
Common mistake
x = 5
if x > 3:
print("big")
else x <= 3:
print("small")Why: else takes no condition; only a colon. With a condition Python cannot parse the line.
How to write it: Drop the condition (else:), or use elif x <= 3: if you really need another test.
Common mistake
n = 7
if n > 5:
print("big")
print("done")
else:
print("small")Why: The unindented print ends the if, so the else has no if to belong to.
How to write it: Put the else right after the if block, at the same indentation level.
