if, elif, else
A conditional statement that runs different code depending on conditions.
Example
#points = 72
if points >= 90:
grade = "excellent"
elif points >= 75:
grade = "good"
elif points >= 50:
grade = "passing"
else:
grade = "needs improvement"
print(f"Score {points} pts: {grade}")Definition and usage
#The if statement runs a block of code only when the condition is true. You check further conditions in elif branches, and else handles every remaining case. Checking stops at the first condition that is met.
In Python, blocks are marked by indentation, not curly braces. You put a colon after the condition, and indent the code inside the block, usually by four spaces. Inconsistent indentation is one of the most common mistakes beginners make.
A condition can be any value. Empty values (0, "", [], {}, None) count as false, and everything else counts as true. For simple cases there is also a one-line conditional expression: a if condition else b.
Syntax
#if condition:
...
elif other_condition:
...
else:
...More examples
#tasks = []
status = "all done" if not tasks else f"{len(tasks)} left"
print(status)
name = ""
print(name or "Guest")Good practices
#- Combine conditions with
and,or, andnot; you can also chain comparisons:0 <= x < 10. - Instead of a long
elifchain comparing one variable against many values, consider a dictionary ormatch.
Related entries
#- match, casePattern matching: choosing a branch of code based on a value’s data and shape.
- whileA loop that repeats a block of code while a condition is true.
- bool()Converts a value to True or False according to the rules of truthiness.
- assertChecks an assumption in the code and raises AssertionError when it does not hold.
Spotted a mistake or missing an example? Write to us.