Real-world programs rarely do the same thing every time they run. A login system needs to check whether a password is correct. A game needs to check whether the player has won. A shopping site needs to check whether an item is in stock. All of these require conditionals — instructions that choose between different actions based on whether something is true or false.
if and else
The simplest conditional is an if statement. The indented block only runs when the condition is True:
score = 75
if score >= 50:
print("You passed!")
If you also want something to happen when the condition is False, add an else block:
if score >= 50:
print("You passed!")
else:
print("You did not pass. Try again.")
Exactly one of the two blocks will run — never both, never neither (as long as the code reaches this point).
The condition after if must evaluate to a Boolean value — either True or False. Comparison operators like == (equals), != (not equals), >, <, >=, and <= all return a Boolean result.
elif: Checking Multiple Conditions
When you have more than two possibilities, use elif (short for "else if") to chain conditions together:
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
Python checks each condition from top to bottom. The moment it finds one that is True, it runs that block and skips the rest. Only one block ever runs.
Order matters with elif. Put the most specific (or strictest) condition first. If you put score >= 60 before score >= 90, every score of 90 or above would match the first condition and never reach the A grade check.
Boolean Conditions
You can combine conditions using the logical operators and, or, and not:
| Operator | Meaning | Example |
|---|---|---|
and | Both must be true | age >= 13 and age <= 17 |
or | At least one must be true | colour == "red" or colour == "blue" |
not | Reverses the result | not is_logged_in |
age = 15
has_ticket = True
if age >= 13 and has_ticket:
print("You may enter.")
else:
print("Sorry, you cannot enter.")
A common mistake is using = (assignment) instead of == (comparison) inside a condition. Writing if score = 50: is a syntax error in Python. Always use == when you are checking whether two values are equal.
Nested Conditionals
You can place an if statement inside another if block. This is called nesting:
if has_ticket:
if age >= 18:
print("Adult ticket — full access.")
else:
print("Child ticket — restricted access.")
else:
print("No ticket — please purchase one.")
Nesting is useful, but too many levels make code hard to read. If you find yourself nesting more than two or three levels deep, it is usually a sign the logic could be restructured.
Practice Problems
What will this code print if temperature = 22? if temperature > 30: print('Hot') elif temperature > 20: print('Warm') else: print('Cool')
Show answer
Write a condition that is True only when a number called n is between 1 and 10 inclusive.