If, Elif, and Else
Conditional branching in Python -- indentation-based blocks, elif chains, and comparison operators.
2 min read
Conditionals let a program make decisions. Python's version reads closer to plain English than most languages, and it uses indentation instead of braces to mark what belongs inside each branch.
The basic form
age = 20
if age >= 18:
print("You're an adult.")
else:
print("You're a minor.")Notice there are no parentheses required around the condition and no braces around the block — the colon (:) starts the block, and everything indented underneath belongs to it. Python enforces consistent indentation; mixing tabs and spaces, or indenting inconsistently, raises an IndentationError. Stick to 4 spaces per level, which is the near-universal convention in Python code.
Chaining conditions with elif
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # Belif (short for "else if") lets you check additional conditions in order. Python checks each one top to bottom and stops at the first True — even if a later condition would also match, it never runs once an earlier branch has already fired.
Comparison and logical operators
x = 5
x == 5 # equal to
x != 5 # not equal to
x > 3 and x < 10 # both must be true
x < 0 or x > 100 # either can be true
not x == 5 # negates the whole expressionPython spells out and, or, and not as words rather than symbols like &&, ||, ! — one more example of the language favoring readability. You can also chain comparisons directly, which is unusual compared to most languages:
if 0 < x < 10:
print("single digit, positive")That's equivalent to 0 < x and x < 10, but reads more naturally.
Truthiness in conditions
Any value can act as a condition, not just actual booleans — recall from the type conversion lesson that empty collections, 0, empty strings, and None are all falsy:
items = []
if items:
print("Processing items")
else:
print("Nothing to process")This is idiomatic Python — checking if items: rather than if len(items) > 0:.
Conditional expressions (the "ternary")
For a simple either/or assignment, a full if/else block can be overkill:
status = "adult" if age >= 18 else "minor"This single-line form is called a conditional expression. It's most readable for short, simple choices — reach for a full if/else block once either branch needs more than one line.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.