If statements¶
In this tutorial, you will learn how to use if, elif, and else to make decisions in your Python code.
Time commitment: 15–20 minutes
Prerequisites:
- Python 3.12 or later installed on your machine
- Basic familiarity with Python syntax (variables, strings, numbers)
Learning objectives¶
By the end of this tutorial, you will be able to:
- Write
ifstatements to execute code conditionally - Use
elifandelseto handle multiple conditions - Use comparison operators to compare values
- Combine conditions with
and,or, andnot
What is conditional logic?¶
Conditional logic allows your program to make decisions. Instead of running every line of code in order, you can tell Python to run certain code only when a condition is met.
Think of it like everyday decisions: "If it is raining, take an umbrella. Otherwise, wear sunglasses."
Your first if statement¶
An if statement checks whether a condition is true. If it is, the indented code beneath it runs:
temperature = 35
if temperature > 30:
print("It is hot today!")
The condition temperature > 30 evaluates to True, so the print statement runs. Try changing the temperature to 20 and running the cell again — you will see that nothing is printed.
Adding an else clause¶
Use else to specify what should happen when the condition is False:
temperature = 15
if temperature > 30:
print("It is hot today!")
else:
print("It is not too hot today.")
Now the program always prints something — one message if the temperature is above 30, and a different message otherwise.
Multiple conditions with elif¶
When you have more than two possible outcomes, use elif (short for "else if") to check additional conditions:
temperature = 15
if temperature > 30:
print("It is hot!")
elif temperature > 20:
print("It is warm.")
elif temperature > 10:
print("It is mild.")
else:
print("It is cold!")
Python checks each condition from top to bottom. As soon as one condition is True, it runs that block and skips the rest. If no conditions are True, the else block runs.
Try changing the temperature and running the cell again to see different results.
Comparison operators¶
Conditions use comparison operators to compare values. Here are the main ones:
| Operator | Meaning | Example |
|---|---|---|
== |
Equal to | x == 5 |
!= |
Not equal to | x != 5 |
> |
Greater than | x > 5 |
< |
Less than | x < 5 |
>= |
Greater than or equal to | x >= 5 |
<= |
Less than or equal to | x <= 5 |
Let's see some in action:
score = 75
if score >= 70:
print("You passed with distinction!")
elif score >= 50:
print("You passed.")
else:
print("You did not pass this time.")
Combining conditions¶
You can combine multiple conditions using boolean operators:
and— both conditions must be trueor— at least one condition must be truenot— reverses a condition
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the event!")
elif age >= 18 and not has_ticket:
print("You need a ticket to enter.")
else:
print("Sorry, you must be at least 18.")
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It is the weekend!")
else:
print("It is a weekday.")
Checking equality with strings¶
You can compare strings just like numbers. Remember that string comparisons are case-sensitive:
colour = "red"
if colour == "red":
print("Stop!")
elif colour == "amber":
print("Get ready...")
elif colour == "green":
print("Go!")
else:
print(f"Unknown colour: {colour}")
Nested if statements¶
You can place if statements inside other if statements. This is called nesting:
is_member = True
age = 15
if is_member:
if age >= 18:
print("Full access granted.")
else:
print("Junior access granted.")
else:
print("Please sign up to become a member.")
While nesting works, deeply nested conditions can become hard to read. In later guides, you will learn techniques for keeping your conditions simple and readable.
Exercise: classify a number¶
Now it is your turn! Write code that takes a number and prints whether it is:
- Positive and even
- Positive and odd
- Zero
- Negative
Hint: Use the modulo operator % to check if a number is even. A number is even if number % 2 == 0.
number = 7 # Try different values
# Write your code here
Solution¶
Here is one way to complete the exercise:
number = 7
if number > 0:
if number % 2 == 0:
print(f"{number} is positive and even")
else:
print(f"{number} is positive and odd")
elif number == 0:
print("The number is zero")
else:
print(f"{number} is negative")
Summary¶
In this tutorial, you learned how to:
- Write
ifstatements to run code only when a condition is true - Use
elsefor a fallback when the condition is false - Use
elifto check multiple conditions in sequence - Compare values with
==,!=,>,<,>=, and<= - Combine conditions with
and,or, andnot - Nest
ifstatements for more complex decisions
What is next¶
In upcoming tutorials, you will explore:
- Boolean expressions — deeper dive into
True,False, and truthiness - Truthiness and falsiness — how Python decides what counts as true
- Match statements — a powerful alternative to long
if/elifchains (Python 3.10 and later)