Master decision-making in Python with if, elif, else statements and boolean logic
Conditional statements allow your program to make decisions and execute different code blocks based on whether certain conditions are true or false. They are fundamental to creating dynamic, responsive programs.
Analogy: Think of conditionals as crossroads where your program decides which path to take based on certain conditions, much like choosing which route to drive based on traffic conditions.
# Simple if statement
temperature = 30
if temperature > 25:
print("It's a hot day!")
# if-else statement
age = 17
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
# if-elif-else statement
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is: {grade}")
Python conditional statements follow a specific syntax that's different from many other programming languages. The most notable difference is the use of indentation instead of braces to define code blocks.
if keyword followed by a condition and a colonelif (else if) clauses can follow with their own conditionselse clause can be included at the endTrue or Falseif condition1:
# Code block executed if condition1 is True
statement1
statement2
...
elif condition2:
# Code block executed if condition2 is True
statement3
statement4
...
else:
# Code block executed if all conditions are False
statement5
statement6
...
Important: Python uses indentation to define code blocks. Unlike other languages that use braces {}, incorrect indentation in Python will cause syntax errors or logical errors.
# Correct indentation (4 spaces)
if True:
print("This is properly indented")
print("This is also part of the if block")
print("This is outside the if block")
# Incorrect indentation
if True:
print("This will cause an IndentationError") # Missing indentation
print("This might cause unexpected behavior") # Inconsistent indentation
Conditional statements rely on operators to evaluate conditions. Python provides several types of operators for creating Boolean expressions.
| Operator | Description | Example | Result |
|---|---|---|---|
== |
Equal to | 5 == 5 |
True |
!= |
Not equal to | 5 != 3 |
True |
> |
Greater than | 5 > 3 |
True |
< |
Less than | 5 < 3 |
False |
>= |
Greater than or equal to | 5 >= 5 |
True |
<= |
Less than or equal to | 5 <= 3 |
False |
| Operator | Description | Example | Result |
|---|---|---|---|
and |
Returns True if both statements are true | (5 > 3) and (5 < 10) |
True |
or |
Returns True if one of the statements is true | (5 > 3) or (5 < 2) |
True |
not |
Reverse the result, returns False if the result is true | not(5 > 3) |
False |
# Using comparison operators
age = 25
if age >= 18 and age <= 65:
print("You are of working age")
# Using logical operators
is_weekend = True
has_money = False
if is_weekend and has_money:
print("Let's go out!")
elif is_weekend and not has_money:
print("Let's find free activities")
else:
print("It's a regular day")
# Combining operators
temperature = 22
is_sunny = True
if temperature > 20 and temperature < 30 and is_sunny:
print("Perfect weather for outdoor activities!")
Here are some practical examples of conditional statements in real-world scenarios.
age = 19
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 65:
print("Adult")
else:
print("Senior")
User Input
purchase_amount = 150
if purchase_amount > 200:
discount = 0.2
elif purchase_amount > 100:
discount = 0.1
else:
discount = 0
final_price = purchase_amount * (1 - discount)
print(f"Final price: ${final_price:.2f}")
E-commerce
temperature = -5
is_raining = True
if temperature < 0:
print("It's freezing! Wear a heavy coat.")
if is_raining:
print("And it's snowing!")
elif temperature < 15:
print("It's cool. A jacket would be good.")
else:
print("It's warm. Enjoy the weather!")
Weather App
password = "SecureP@ss123"
if len(password) < 8:
strength = "Weak"
elif len(password) < 12:
# Check for complexity
has_upper = any(char.isupper() for char in password)
has_lower = any(char.islower() for char in password)
has_digit = any(char.isdigit() for char in password)
has_special = any(not char.isalnum() for char in password)
if has_upper and has_lower and has_digit and has_special:
strength = "Strong"
else:
strength = "Medium"
else:
strength = "Very Strong"
print(f"Password strength: {strength}")
Nested conditionals are if statements inside other if statements. They allow for more complex decision-making by checking multiple conditions in a hierarchical manner.
# Checking eligibility for a driver's license
age = 17
has_permit = True
passed_test = False
if age >= 16:
if has_permit:
if passed_test:
print("You can get your driver's license!")
else:
print("You need to pass the driving test first.")
else:
print("You need a learner's permit first.")
else:
print("You are too young to drive.")
Sometimes you can use logical operators instead of nesting for simpler code:
# Nested conditions
x = 10
y = 5
if x > 0:
if y > 0:
print("Both x and y are positive")
else:
print("x is positive but y is not")
else:
print("x is not positive")
# Using logical operators
x = 10
y = 5
if x > 0 and y > 0:
print("Both x and y are positive")
elif x > 0:
print("x is positive but y is not")
else:
print("x is not positive")
Recommendation: While nested conditionals are powerful, avoid going too deep (more than 2-3 levels) as they can make code difficult to read and maintain. Consider using compound conditions or refactoring into functions for complex logic.
username = "admin"
password = "secure123"
is_2fa_enabled = True
otp_code = "123456"
# Simulating a login process
if username == "admin":
if password == "secure123":
if is_2fa_enabled:
if otp_code == "123456":
print("Login successful!")
else:
print("Invalid OTP code.")
else:
print("Login successful! (2FA not enabled)")
else:
print("Incorrect password.")
else:
print("User not found.")
Python provides a concise way to write simple if-else statements in a single line using the ternary operator.
# Traditional if-else
if condition:
value_if_true
else:
value_if_false
# Ternary operator
value = value_if_true if condition else value_if_false
# Traditional if-else
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
# Traditional if-else
number = 7
if number % 2 == 0:
result = "even"
else:
result = "odd"
# Ternary operator
age = 20
status = "adult" if age >= 18 else "minor"
# Ternary operator
number = 7
result = "even" if number % 2 == 0 else "odd"
Avoid Nesting Ternary Operators: While technically possible, nested ternary operators are difficult to read and understand. Use traditional if-else statements for complex conditions.
# Difficult to read nested ternary
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
# Better approach with if-elif-else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Even experienced developers can make mistakes with conditional statements. Here are some common errors to avoid.
# Wrong - This assigns 5 to x, which is always truthy
if x = 5:
print("x is 5")
# Correct - This compares x to 5
if x == 5:
print("x is 5")
# Wrong - The print statement is not properly indented
if True:
print("This will cause an IndentationError")
# Correct - Proper indentation
if True:
print("This will work correctly")
# Wrong - Missing colon after condition
if True
print("This will cause a SyntaxError")
# Correct - Colon included
if True:
print("This works")
# Wrong - This doesn't work as expected
if 10 < x < 20: # Actually correct in Python!
print("x between 10 and 20")
# Surprisingly, Python supports chained comparisons!
# The above code is actually correct
# What doesn't work is:
# if x > 10 and < 20: # SyntaxError
# Correct approach for languages without chained comparisons:
if x > 10 and x < 20:
print("x between 10 and 20")
Python Tip: Unlike many other languages, Python supports chained comparison operators like 10 < x < 20, which is equivalent to x > 10 and x < 20.
In Python, values evaluate to True or False in a Boolean context. Understanding which values are "truthy" or "falsy" is important.
# Falsy values in Python
false_values = [False, None, 0, 0.0, "", [], (), {}, set()]
for value in false_values:
if value:
print(f"{value} is truthy")
else:
print(f"{value} is falsy")
# Wrong for value comparison - 'is' checks identity, not equality
x = [1, 2, 3]
y = [1, 2, 3]
if x is y: # False - they are different objects
print("Same object")
if x == y: # True - they have the same value
print("Equal values")
Follow these best practices to write clean, maintainable, and efficient conditional code.
# Hard to read
if (user.is_authenticated and user.has_permission('edit') and
not article.is_locked and (article.author == user or user.is_admin)):
# complex logic
# Better - break into variables or functions
can_edit = user.is_authenticated and user.has_permission('edit')
is_unlocked = not article.is_locked
is_author_or_admin = article.author == user or user.is_admin
if can_edit and is_unlocked and is_author_or_admin:
# complex logic
# Hard to understand
if not user.is_not_verified: # Double negative
# do something
# Better - positive condition
if user.is_verified:
# do something
# Nested conditions
def process_data(data):
if data is not None:
if len(data) > 0:
if validate(data):
# main logic here
return result
else:
return None
else:
return None
else:
return None
# Better - early returns
def process_data(data):
if data is None:
return None
if len(data) == 0:
return None
if not validate(data):
return None
# main logic here
return result
# Unclear
if x > y and z < 0:
# do something
# Better
is_profit = revenue > expenses
is_discounted = discount_rate > 0
if is_profit and is_discounted:
# do something
# Hard to follow deep nesting
if condition1:
if condition2:
if condition3:
if condition4:
# code deep inside
# Better - flatten with logical operators
if condition1 and condition2 and condition3 and condition4:
# code at top level
Follow PEP 8 style guide for conditional statements:
# Check if user can access premium content
# Conditions: subscribed, not expired, and not exceeded usage limit
has_access = (user.is_subscribed and
not user.subscription_expired and
user.usage_count < user.usage_limit)