Making Decisions with if/else
Run different code depending on what's true
Programs get interesting when they can make choices. The if statement lets your code run only when a condition is true.
The shape of an if
age = 20
if age >= 18:
print("You are an adult.")Read it as plain English: "if age is greater than or equal to 18, then show that message." Two things to notice:
- The line ends with a colon
: - The line below is indented (pushed in with spaces). That indentation is how Python knows which code belongs to the
if. It's not decoration — it's required.
Adding else
else covers the "otherwise" case — what to do when the condition is not true:
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")Comparing values
These are the comparison operators you'll use:
==equal to (yes, two equals signs — one is for storing)!=not equal to>greater than,<less than>=greater than or equal,<=less than or equal
Checking more cases with elif
elif (short for "else if") lets you check extra conditions in order:
score = 75
if score >= 90:
print("Grade A")
elif score >= 70:
print("Grade B")
else:
print("Keep going!")Tip: Use == to compare and = to store. Mixing them up is one of the most common beginner mistakes. age = 18 sets age; age == 18 asks a question.
Your turn
Change the value of score and see which message prints.
Press “Run code” to see the result.
Quick check
Q1 Which operator checks whether two values are EQUAL?
Q2 Why is the line under an if indented (pushed in with spaces)?
Want to save your progress? It's free.
Create a free account