if, elif, else

A conditional statement that runs different code depending on conditions.

On this page

Example

#
Python
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}")
Resultsaved result, you can check it
Score 72 pts: passing

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

#
Syntax
if condition:
    ...
elif other_condition:
    ...
else:
    ...

More examples

#
Conditional expression and empty values
Python
tasks = []
status = "all done" if not tasks else f"{len(tasks)} left"
print(status)

name = ""
print(name or "Guest")
Resultsaved result, you can check it
all done
Guest

Good practices

#
  • Combine conditions with and, or, and not; you can also chain comparisons: 0 <= x < 10.
  • Instead of a long elif chain comparing one variable against many values, consider a dictionary or match.

Related entries

#

Spotted a mistake or missing an example? Write to us.