Python — If Else
The if statement
Python's if statement runs code only when a condition is true:
age = 25
if age >= 18:
print("You are an adult.")
The condition must evaluate to a truthy or falsy value. No parentheses needed around the condition.
The if-else statement
temperature = 5
if temperature > 30:
print("It's hot outside.")
else:
print("It's not that hot.")
One of the two blocks always executes. Indentation defines which code belongs to which branch.
elif chains
score = 78
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Python evaluates conditions top to bottom and runs the first matching block. The rest are skipped. No limit to how many elif branches you can have.
Ternary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
Format: value_if_true if condition else value_if_false. Use it for simple assignments. For complex logic, use a regular if-else block.
Nested conditions
has_ticket = True
age = 16
if has_ticket:
if age >= 18:
print("Welcome to the show.")
else:
print("You need a guardian.")
else:
print("Please buy a ticket first.")
Nesting works but becomes hard to read beyond two levels. Combine conditions with and/or when possible:
if has_ticket and age >= 18:
print("Welcome!")
elif has_ticket:
print("Need a guardian.")
else:
print("Buy a ticket.")
Truthy and falsy values
Python treats certain values as false in conditions:
# Falsy values
if 0: print("This won't print")
if "": print("This won't print")
if []: print("This won't print")
if {}: print("This won't print")
if None: print("This won't print")
# Truthy values
if 1: print("This prints")
if "hello": print("This prints")
if [1, 2]: print("This prints")
if {"a": 1}: print("This prints")
This means you can write clean boolean checks:
# Instead of:
if len(items) > 0:
process(items)
# Write:
if items:
process(items)
The match statement (Python 3.10+)
day = "Monday"
match day:
case "Saturday" | "Sunday":
print("Weekend")
case "Monday":
print("Start of the week")
case "Friday":
print("TGIF!")
case _:
print("Regular day")
match is Python's structural pattern matching. It handles multiple patterns cleanly and can destructure data:
point = (1, 0)
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"On x-axis at {x}")
case (0, y):
print(f"On y-axis at {y}")
case (x, y):
print(f"At ({x}, {y})")
Chained comparisons
Python allows chaining comparisons — unusual but useful:
x = 5
# Chained comparison
if 1 < x < 10:
print("Between 1 and 10")
# Multiple conditions
if 0 <= x <= 100 and x % 2 == 0:
print("Even number between 0 and 100")
Short-circuit evaluation
Python evaluates and and or lazily:
# and — stops at first False
result = False and expensive_function() # never calls the function
# or — stops at first True
result = True or expensive_function() # never calls the function
# Practical use — safe attribute access
name = user and user.get("name") or "Anonymous"
Common mistakes
Forgetting the colon
if age >= 18 # SyntaxError: expected ':'
print("Adult")
Every if, elif, else, for, while, def, and class line must end with a colon.
Comparing with = instead of ==
x = 5
# if x = 5: # SyntaxError: invalid syntax
if x == 5: # correct
Python catches this — assignment is a statement, not an expression.
Mutating a list while iterating
# Bad — modifies the list while iterating
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
numbers.remove(n) # unpredictable behavior!
# Good — create a new list
numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 != 0]
Combining conditions
age = 25
has_id = True
is_vip = False
# AND — all must be true
if age >= 18 and has_id:
print("Entry allowed")
# OR — at least one must be true
if is_vip or age >= 65:
print("Priority lane")
# NOT — flips the boolean
if not is_vip:
print("Standard lane")
if-elif-else as an expression
score = 85
# As an expression
result = (
"A" if score >= 90 else
"B" if score >= 80 else
"C" if score >= 70 else
"D" if score >= 60 else
"F"
)
print(result) # B
Nested ternaries can be hard to read — use sparingly.
Mini Practice
- Write a program that classifies a number as positive, negative, or zero
- Create a temperature converter that recommends clothing based on the temperature
- Use a ternary expression to assign "even" or "odd" to a variable
- Write a grade calculator with if-elif-else
- Use match-case to categorize a day of the week as "Weekday", "Weekend", or "Invalid"
Next: loops — repeating actions →
Related Topics
Frequently Asked Questions about If Else
What is If Else in Python?
If Else is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn If Else?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn If Else.
Why is If Else important in Python?
If Else is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.