Conditions
Choose which code runs using comparisons and if, elif, and else.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
A condition is an expression that Python evaluates as true or false. An if block runs only when its condition is true. Use elif for another test and else for the remaining case.
A colon ends each branch header, and indentation marks the statements inside that branch. Use == to compare values; = assigns a value to a name.
- if, elif, and else
- Boolean comparisons
- Indented blocks
See it step by step
Read the code, predict the output, then compare it with the result.
01. Choose one branch
temperature = 30
if temperature >= 30:
print("Hot")
else:
print("Mild")HotThe condition is true, so Python runs the indented first branch and skips else.
02. Use elif
points = 75
if points >= 90:
print("Excellent")
elif points >= 60:
print("Passed")
else:
print("Try again")PassedPython checks the conditions in order. Only the first matching branch runs.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Place if score == 100 first. Change the old if score >= 90 to elif score >= 90, keep the remaining elif and else, then test with score = 100.
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Missing colon
score = 75
if score >= 60
print("Passed")score = 75
if score >= 60:
print("Passed")What happens: SyntaxError on the if line.
End the if header with a colon.
Missing indentation
score = 75
if score >= 60:
print("Passed")score = 75
if score >= 60:
print("Passed")What happens: IndentationError after the if header.
Indent statements that belong to the branch.