Conditional statements are fundamental to programming logic in Python. They allow your programs to make decisions, execute different code paths, and respond intelligently to varying inputs and conditions. Whether you're building a simple calculator or a complex data analysis tool, mastering if, else, and elif statements is essential.
This comprehensive guide will teach you everything you need to know about Python's conditional statements, from basic syntax to advanced patterns and best practices.
What are Conditional Statements?
Conditional statements are code structures that execute specific blocks of code only when certain conditions are met. They enable your programs to:
- Make decisions based on user input
- Validate data before processing
- Handle different scenarios appropriately
- Control program flow dynamically
- Respond to changing conditions
Python provides three keywords for conditional logic:
if- Execute code when a condition is Trueelif- Check additional conditions (short for "else if")else- Execute code when all conditions are False
The if Statement
The simplest conditional statement is if. It executes a block of code only when a specified condition evaluates to True.
Basic Syntax
if condition:
# Code to execute if condition is True
statement1
statement2
Important: Python uses indentation (typically 4 spaces) to define code blocks. All indented statements after the if are part of the conditional block.
Simple Example
age = 20
if age >= 18:
print("You are an adult.")
print("You can vote.")
# Output:
# You are an adult.
# You can vote.
If the condition is False, the indented block is skipped:
age = 15
if age >= 18:
print("You are an adult.")
print("This always runs.")
# Output:
# This always runs.
Comparison Operators
Conditions typically use comparison operators to evaluate expressions:
| 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 |
Examples
temperature = 75
if temperature > 80:
print("It's hot outside!")
if temperature <= 80:
print("The temperature is comfortable.")
# Output: The temperature is comfortable.
The else Statement
The else statement provides an alternative block of code that executes when the if condition is False.
Syntax
if condition:
# Execute if condition is True
else:
# Execute if condition is False
Example
age = 15
if age >= 18:
print("You can vote.")
else:
print("You are not old enough to vote yet.")
# Output: You are not old enough to vote yet.
Practical Example: Even or Odd
number = 7
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
# Output: 7 is odd.
The elif Statement (else-if)
When you need to check multiple conditions sequentially, use elif (short for "else if"). Python evaluates conditions from top to bottom and executes the first True block, then skips the rest.
Syntax
if condition1:
# Execute if condition1 is True
elif condition2:
# Execute if condition1 is False and condition2 is True
elif condition3:
# Execute if condition1 and condition2 are False and condition3 is True
else:
# Execute if all conditions are False
Example: Grade Calculator
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")
# Output: Your grade is: B
How elif Works
Once a condition is True, Python executes that block and skips all remaining elif and else blocks, even if their conditions would also be True.
number = 15
if number > 10:
print("Number is greater than 10")
elif number > 5:
print("Number is greater than 5") # This won't execute
else:
print("Number is 5 or less") # This won't execute
# Output: Number is greater than 10
Multiple Conditions with Logical Operators
You can combine multiple conditions using logical operators:
and Operator
Both conditions must be True:
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
else:
print("You cannot drive.")
# Output: You can drive.
or Operator
At least one condition must be True:
is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("No work today!")
else:
print("Time to work.")
# Output: No work today!
not Operator
Negates a condition:
is_raining = False
if not is_raining:
print("You don't need an umbrella.")
else:
print("Take an umbrella.")
# Output: You don't need an umbrella.
Combining Multiple Operators
age = 25
has_ticket = True
has_id = True
if age >= 18 and (has_ticket and has_id):
print("You can enter the venue.")
elif age >= 18 and not has_ticket:
print("You need to buy a ticket.")
else:
print("You are not old enough to enter.")
# Output: You can enter the venue.
Nested if Statements
You can place if statements inside other if statements to create more complex decision trees.
Syntax
if condition1:
if condition2:
# Execute if both condition1 and condition2 are True
else:
# Execute if condition1 is True but condition2 is False
else:
# Execute if condition1 is False
Example: Authentication System
username = "admin"
password = "secure123"
if username == "admin":
if password == "secure123":
print("Access granted!")
else:
print("Incorrect password.")
else:
print("User not found.")
# Output: Access granted!
Example: BMI Calculator
weight = 70 # kg
height = 1.75 # meters
bmi = weight / (height ** 2)
if bmi < 18.5:
category = "Underweight"
if bmi < 16:
print("Severely underweight - please consult a doctor")
else:
print("Underweight - consider gaining weight")
elif bmi < 25:
category = "Normal"
print("Healthy weight - keep it up!")
elif bmi < 30:
category = "Overweight"
print("Overweight - consider lifestyle changes")
else:
category = "Obese"
if bmi >= 35:
print("Severely obese - please consult a doctor")
else:
print("Obese - consider medical advice")
print(f"BMI: {bmi:.1f} - Category: {category}")
# Output:
# Healthy weight - keep it up!
# BMI: 22.9 - Category: Normal
Note: Deep nesting (more than 2-3 levels) can make code hard to read. Consider refactoring into functions or simplifying logic.
Ternary Conditional Expression (One-Line if-else)
Python supports a compact one-line syntax for simple if-else statements:
Syntax
value_if_true if condition else value_if_false
Examples
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # Output: adult
# Traditional equivalent:
if age >= 18:
status = "adult"
else:
status = "minor"
number = -5
result = "positive" if number > 0 else "negative or zero"
print(result) # Output: negative or zero
temperature = 75
clothing = "light clothes" if temperature > 70 else "warm clothes"
print(f"Wear {clothing}") # Output: Wear light clothes
Limitation: Ternary expressions only work for simple if-else (no elif support).
Truthy and Falsy Values
In Python, not all conditions explicitly use comparison operators. Python evaluates values as "truthy" or "falsy" in boolean contexts.
Falsy Values
These values evaluate to False:
NoneFalse- Zero of any numeric type:
0,0.0,0j - Empty sequences:
'',[],() - Empty mappings:
{} - Empty sets:
set()
Truthy Values
All other values evaluate to True, including:
- Non-zero numbers
- Non-empty strings, lists, tuples, dictionaries
True
Examples
username = ""
if username:
print(f"Hello, {username}!")
else:
print("Please enter a username.")
# Output: Please enter a username.
items = [1, 2, 3]
if items:
print("The list has items.")
else:
print("The list is empty.")
# Output: The list has items.
value = None
if value:
print("Value exists.")
else:
print("Value is None or empty.")
# Output: Value is None or empty.
Practical Examples
Example 1: Login System
def authenticate(username, password):
"""Simple authentication function"""
valid_users = {
"admin": "admin123",
"user": "pass123"
}
if username not in valid_users:
return "Error: User not found"
elif valid_users[username] != password:
return "Error: Incorrect password"
else:
return f"Welcome, {username}!"
# Test the function
print(authenticate("admin", "admin123")) # Output: Welcome, admin!
print(authenticate("user", "wrong")) # Output: Error: Incorrect password
print(authenticate("guest", "123")) # Output: Error: User not found
Example 2: Discount Calculator
def calculate_discount(total, customer_type):
"""Calculate discount based on customer type and total"""
if total < 0:
return "Error: Invalid total"
if customer_type == "VIP":
if total >= 1000:
discount = 0.30
elif total >= 500:
discount = 0.20
else:
discount = 0.15
elif customer_type == "Regular":
if total >= 500:
discount = 0.10
else:
discount = 0.05
else:
discount = 0.0 # No discount for guests
final_total = total * (1 - discount)
return f"Original: ${total:.2f}, Discount: {discount*100:.0f}%, Final: ${final_total:.2f}"
print(calculate_discount(1200, "VIP"))
# Output: Original: $1200.00, Discount: 30%, Final: $840.00
print(calculate_discount(300, "Regular"))
# Output: Original: $300.00, Discount: 5%, Final: $285.00
Example 3: Temperature Converter with Validation
def convert_temperature(value, from_unit, to_unit):
"""Convert temperature between Celsius, Fahrenheit, and Kelvin"""
# Validate input
if from_unit not in ["C", "F", "K"] or to_unit not in ["C", "F", "K"]:
return "Error: Invalid unit. Use C, F, or K."
# Check absolute zero
if from_unit == "C" and value < -273.15:
return "Error: Temperature below absolute zero"
elif from_unit == "F" and value < -459.67:
return "Error: Temperature below absolute zero"
elif from_unit == "K" and value < 0:
return "Error: Temperature below absolute zero"
# Convert to Celsius first
if from_unit == "F":
celsius = (value - 32) * 5/9
elif from_unit == "K":
celsius = value - 273.15
else:
celsius = value
# Convert from Celsius to target unit
if to_unit == "F":
result = celsius * 9/5 + 32
elif to_unit == "K":
result = celsius + 273.15
else:
result = celsius
return f"{value}°{from_unit} = {result:.2f}°{to_unit}"
print(convert_temperature(100, "C", "F")) # Output: 100°C = 212.00°F
print(convert_temperature(32, "F", "C")) # Output: 32°F = 0.00°C
print(convert_temperature(-300, "C", "K")) # Output: Error: Temperature below absolute zero
Example 4: Traffic Light System
def traffic_light(color, pedestrian_waiting=False):
"""Determine action based on traffic light color"""
color = color.lower()
if color == "green":
if pedestrian_waiting:
return "Proceed with caution - pedestrian may cross"
else:
return "Go - traffic is clear"
elif color == "yellow":
return "Slow down - light will turn red soon"
elif color == "red":
return "Stop - wait for green light"
else:
return "Error: Invalid traffic light color"
print(traffic_light("green"))
# Output: Go - traffic is clear
print(traffic_light("green", pedestrian_waiting=True))
# Output: Proceed with caution - pedestrian may cross
print(traffic_light("red"))
# Output: Stop - wait for green light
Common Mistakes and How to Avoid Them
1. Using = Instead of ==
# Wrong - This assigns 5 to x, doesn't compare
if x = 5: # SyntaxError
print("x is 5")
# Correct - This compares x to 5
if x == 5:
print("x is 5")
2. Forgetting Indentation
# Wrong - IndentationError
if age >= 18:
print("You can vote")
# Correct
if age >= 18:
print("You can vote")
3. elif Without if
# Wrong - SyntaxError
elif x > 5:
print("Greater than 5")
# Correct
if x > 10:
print("Greater than 10")
elif x > 5:
print("Greater than 5")
4. Confusing if with elif
x = 15
# Multiple if statements - all conditions are checked
if x > 10:
print("Greater than 10") # Executes
if x > 5:
print("Greater than 5") # Also executes
# if-elif chain - only first True condition executes
if x > 10:
print("Greater than 10") # Executes
elif x > 5:
print("Greater than 5") # Skipped
5. Not Using Parentheses for Complex Conditions
# Confusing
if age >= 18 and has_license or has_permit:
# Is it (age >= 18 and has_license) or has_permit?
# Or age >= 18 and (has_license or has_permit)?
pass
# Clear
if (age >= 18 and has_license) or has_permit:
pass
Best Practices
1. Keep Conditions Simple and Readable
# Bad - Hard to read
if not (age < 18 or not has_license):
drive()
# Good - Clear intent
if age >= 18 and has_license:
drive()
2. Use Meaningful Variable Names
# Bad
if x and y:
z = True
# Good
if user_logged_in and has_permission:
allow_access = True
3. Avoid Deep Nesting
# Bad - Deep nesting
if condition1:
if condition2:
if condition3:
if condition4:
do_something()
# Good - Early returns or combined conditions
if not condition1:
return
if not condition2:
return
if not condition3:
return
if condition4:
do_something()
# Or combine conditions
if condition1 and condition2 and condition3 and condition4:
do_something()
4. Use elif Instead of Multiple ifs for Mutually Exclusive Conditions
# Less efficient - checks all conditions
if score >= 90:
grade = "A"
if score >= 80 and score < 90:
grade = "B"
if score >= 70 and score < 80:
grade = "C"
# Better - stops after first match
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
5. Consider Using Dictionary Mapping for Many Conditions
# Instead of many elif statements
def get_day_name(day_number):
if day_number == 1:
return "Monday"
elif day_number == 2:
return "Tuesday"
elif day_number == 3:
return "Wednesday"
# ... many more
# Better - Dictionary mapping
def get_day_name(day_number):
days = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}
return days.get(day_number, "Invalid day")
Conclusion
Conditional statements (if, elif, else) are fundamental to programming logic in Python. They enable your programs to make intelligent decisions, validate input, handle different scenarios, and control program flow based on dynamic conditions.
Key takeaways:
if- Executes code when a condition is Trueelif- Checks additional conditions sequentially (only if previous conditions were False)else- Provides a fallback when all conditions are False- Use comparison operators (
==,!=,>,<,>=,<=) to create conditions - Combine conditions with logical operators (
and,or,not) - Nested if statements allow complex decision trees
- Ternary expressions provide compact one-line if-else syntax
- Follow best practices: keep conditions simple, use meaningful names, avoid deep nesting
Master these conditional statements, and you'll be able to write Python programs that respond intelligently to any situation. Practice with real-world examples, start simple, and gradually build more complex logic as you become comfortable with the basics.
Happy coding!
