Conditionals in Python
Master conditionals in Python: if, elif, and else, comparison and logical operators, and nested conditions. Make your programs decide and react, with runnable code and a quiz.
Key takeaways
- if runs a block only when a condition is True
- elif checks another condition; else catches everything left over
- Comparison operators (==, !=, <, >, <=, >=) produce True or False
- Combine conditions with and, or, and not
- Indentation defines which lines belong to each branch
Programs that make decisions
So far a program might run the same way every time. Conditionals change that: they let a program choose what to do based on what is true right now. Should the game say "You win" or "Try again"? Should the app show the daytime or the night theme? Conditionals make these decisions.
If you've written a first Python program with variables and input(), you already have everything you need to start.
The if statement
An if statement runs a block of code only when a condition is true:
age = 15
if age >= 13:
print("You are a teenager.")
Read it as: "if age is greater than or equal to 13, print this message." Because age is 15, the condition age >= 13 is True, so the message prints.
Two things to notice:
- The condition ends with a colon
:. - The line below is indented (four spaces). Indentation tells Python which lines belong inside the
if. If the condition is False, those indented lines are skipped.
True and False
A condition is really a question that Python answers with True or False — these are called boolean values. Comparisons produce them:
print(5 > 3) # True
print(2 == 2) # True
print(4 != 4) # False
Here are the comparison operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 3 == 3 | True |
!= | not equal to | 3 != 4 | True |
< | less than | 2 < 5 | True |
> | greater than | 2 > 5 | False |
<= | less than or equal | 5 <= 5 | True |
>= | greater than or equal | 6 >= 9 | False |
Watch out: = assigns a value, but == compares. Writing if x = 5: is an error; you want if x == 5:.
else: the other path
Often you want one thing to happen when the condition is true and a different thing when it's false. That's what else is for:
temperature = 28
if temperature > 25:
print("It's hot — wear shorts.")
else:
print("It's cool — bring a jacket.")
Exactly one of the two branches runs. The else has no condition of its own; it simply catches every case the if didn't.
elif: more than two choices
When there are several possibilities, use elif (short for "else if"). Python checks each condition in order and runs the first one that is true:
score = 82
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
With score = 82, the first test (>= 90) is False, the second (>= 80) is True, so it prints Grade: B and stops — the later branches are not even checked.
Combining conditions with and, or, not
You can join conditions using logical operators:
and— true only if both sides are trueor— true if at least one side is truenot— flips true to false and back
age = 16
if age >= 13 and age <= 19:
print("You are a teen.")
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
logged_in = False
if not logged_in:
print("Please log in.")
In the first example, both sides must be true, so the age must be between 13 and 19 inclusive.
A complete example
Here's a small program that reacts to the user:
age = int(input("How old are you? "))
if age < 0:
print("That's not a valid age.")
elif age < 13:
print("You're a child.")
elif age <= 19:
print("You're a teenager.")
else:
print("You're an adult.")
It reads a number, then chooses exactly one message based on the value. Try running it with different ages and watch which branch wins.
Conditions inside loops
Conditionals get even more powerful inside a loop, where they make a decision on every pass:
for number in range(1, 6):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
number % 2 is the remainder after dividing by 2. If that remainder is 0, the number is even. This is the same loop idea from Loops: Making the Computer Repeat, now making a real decision each time.
Practice challenges
- Ask the user for a number and print whether it is positive, negative, or zero.
- Write a simple password check: if the typed password equals
"open123", print "Access granted", otherwise "Denied". - Ask for a year and print whether it's a leap year. (A year is a leap year if it is divisible by 4 but not by 100, unless it is also divisible by 400.)
Quick quiz
Test yourself and earn XP
What does `==` mean in Python?
A single = assigns a value; == compares two values and gives True or False.
What prints? ``` x = 7 if x > 10: print("big") else: print("small") ```
7 > 10 is False, so the else branch runs and prints small.
When does `age >= 13 and age <= 19` evaluate to True?
and requires both conditions to be True, so age must be at least 13 and at most 19.
What is the role of elif?
elif (else-if) is tested only when the previous if/elif conditions were all False.
What does `not (5 > 3)` give?
5 > 3 is True, and not flips it to False.
FAQ
A single = assigns a value to a variable, like age = 14. A double == compares two values and returns True or False, like age == 14. Mixing them up is one of the most common beginner mistakes.
No. An if can stand alone, and you can have if with one or more elif branches and no else. Use else only when you want a catch-all that runs when nothing above it matched.
Keep exploring
More in Coding