Python if, else and elif Explained
else: The Other Path
An if alone does something or nothing. Add else to do something different when the condition is False:
age = int(input())
if age >= 18:
print("You can vote.")
else:
print("Not yet. Wait a few years!")Not yet. Wait a few years!
Exactly one of the two blocks runs, never both, never neither.
- Start: Start
- Input or output: Read the age
- Decision: Is age 18 or more?yesShow: You can vote.noShow: Not yet.
- End: End
How to write it
elselines up with itsif: same indentation.- It has no condition: it simply means "otherwise".
- It ends with a colon, and its block is indented, just like the
ifblock.
Even or odd
A classic example, using % from chapter 5. A number is even when dividing it by 2 leaves nothing over:
n = int(input())
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")7 is odd
Think of a fork in a road: you must take one way or the other, and you can't take both.
Common beginner doubt: "Can I put more than one line in each block?" Yes. Each block can have as many indented lines as you need: calculations, several print()s, even another if.
if … else: one of the two blocks always runs.