Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
Conditionals let your program make decisions: run one block of code when something is true, and a different block when it’s false.
Use if and a condition. The code that runs when the condition is true is indented (usually 4 spaces):
score = 50
if score >= 50:
print("You passed!")
If score were 30, nothing would print. Only when score >= 50 is True does the indented code run.
In Python, indentation shows which lines belong to the if. Everything that’s indented under if runs only when the condition is True.
if score > 0:
print("Score is positive")
print("Well done")
print("This always runs") # not indented, so not part of the if
Use else to run code when the condition is not true:
age = 12
if age >= 13:
print("You can join")
else:
print("Come back when you're 13")
Use elif to check another condition when the first one was false:
score = 75
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("Keep practising")
Only one of these blocks runs: the first condition that is True.
input() to get the user’s guess (convert to int).if, elif and else to print “Too high!”, “Too low!” or “Correct!”.Navigation
Tasks
if, elif, and else (e.g. menus, grades, tickets; loops come in too on many pages)Tutorial