Learn Python
>>> control_flow.if_else

if, elif, else Statements in Python

#concept

An if statement runs a block of code only when a condition is true. Adding elif ("else if") lets you check additional conditions in sequence, and a final else catches everything that didn't match any prior condition. Python checks conditions top to bottom and runs only the first block whose condition is true, skipping the rest entirely.

#how it works
1

if condition:

Introduces the first check; its block runs only if the condition is truthy.

2

elif condition: (optional, repeatable)

Checks another condition, but only if every earlier condition was false.

3

else: (optional, at most one)

Runs when none of the above conditions were true.

4

Python stops at the first match

Later elif and else blocks are skipped entirely once one condition succeeds.

5

Any number of elif blocks are allowed

Between the opening if and the optional else.

#example
score = 75
 
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Output
Grade: C
1Python checks score >= 90 first — False, since score is 75.
2It checks score >= 80 next — also False.
3It checks score >= 70 — True, so "Grade: C" prints, and Python skips every remaining elif and the else entirely.
4If score had been 95 instead, the very first condition would have matched, and nothing else would even be checked.
#use cases
Grading systems, tiered pricing, or any logic with several distinct outcome bands
Validating input and responding differently to different kinds of invalid data
A menu-driven program that branches based on a user's choice
Any decision in a program with more than two possible outcomes

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.