Conditional statements allow your program to make decisions and execute different code based on certain conditions. They are the foundation of program logic, enabling your code to respond differently to various situations.
Think of conditional statements like a decision tree - your program evaluates a condition and chooses which path to follow based on whether the condition is true or false.
example:
age = 18
if age >= 18:
print("You are eligible to vote!")
else:
print("You are not old enough to vote yet.")
The if
statement is the most basic conditional statement. It executes code only when a condition is true.
# Basic if statement
temperature = 85
if temperature > 80:
print("It's a hot day!")
print("Remember to stay hydrated!")
# Multiple statements can be included in the if block
score = 95
if score >= 90:
print("Excellent work!")
print("You earned an A grade!")
print("Keep up the great performance!")
# Using boolean variables
is_sunny = True
has_umbrella = False
if is_sunny:
print("Great weather for a walk!")
if not has_umbrella:
print("Don't forget to bring an umbrella!")
# Using comparison operators
user_age = 25
required_age = 21
if user_age >= required_age:
print("Access granted!")
The else
clause provides an alternative action when the condition is false.
# Basic if-else
password = "secret123"
if password == "secret123":
print("Login successful!")
else:
print("Invalid password!")
# Checking even or odd numbers
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
# Age-based access control
user_age = 16
if user_age >= 18:
print("Welcome! You can access all content.")
else:
print("Sorry, you must be 18 or older.")
print("Some content is restricted.")
The elif
(else if) statement allows you to check multiple conditions in sequence.
# Multiple conditions with elif
grade = 87
if grade >= 90:
print("Grade: A")
elif grade >= 80:
print("Grade: B")
elif grade >= 70:
print("Grade: C")
elif grade >= 60:
print("Grade: D")
else:
print("Grade: F")
# Weather-based recommendations
temperature = 72
if temperature >= 85:
print("It's hot! Wear light clothing.")
elif temperature >= 70:
print("Perfect weather! Dress comfortably.")
elif temperature >= 50:
print("A bit cool. Consider a light jacket.")
elif temperature >= 32:
print("Cold! Wear warm clothes.")
else:
print("Freezing! Bundle up!")
# User role-based permissions
user_role = "admin"
if user_role == "admin":
print("Full system access granted")
print("Can modify all settings")
elif user_role == "moderator":
print("Moderate access granted")
print("Can moderate content")
elif user_role == "user":
print("Basic access granted")
print("Can view and comment")
elif user_role == "guest":
print("Limited access granted")
print("Can only view content")
else:
print("Unknown role - access denied")
# BMI calculator with categories
height = 5.8 # feet
weight = 160 # pounds
# Calculate BMI
bmi = (weight * 703) / (height * 12) ** 2
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
print(f"Your BMI is {bmi:.1f}")
print(f"Category: {category}")
Python provides various operators to compare values in conditional statements.
# Numeric comparisons
x = 10
y = 20
print(f"x == y: {x == y}") # Equal to
print(f"x != y: {x != y}") # Not equal to
print(f"x < y: {x < y}") # Less than
print(f"x <= y: {x <= y}") # Less than or equal to
print(f"x > y: {x > y}") # Greater than
print(f"x >= y: {x >= y}") # Greater than or equal to
# String comparisons
name1 = "Alice"
name2 = "Bob"
name3 = "Alice"
if name1 == name3:
print("Names are identical")
if name1 != name2:
print("Names are different")
# Case-sensitive comparison
password = "Secret123"
user_input = "secret123"
if password == user_input:
print("Password correct")
else:
print("Password incorrect - remember it's case sensitive!")
# Case-insensitive comparison
if password.lower() == user_input.lower():
print("Password accepted (case-insensitive check)")
Combine multiple conditions using logical operators: and
, or
, and not
.
# 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.")
# Multiple and conditions
username = "john_doe"
password = "secure123"
is_active = True
if username == "john_doe" and password == "secure123" and is_active:
print("Login successful!")
else:
print("Login failed!")
# Range checking with and
score = 85
if score >= 80 and score <= 100:
print("Excellent performance!")
elif score >= 60 and score < 80:
print("Good job!")
else:
print("Keep trying!")
# At least one condition must be true
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday.")
# Multiple or conditions
payment_method = "credit_card"
if payment_method == "cash" or payment_method == "credit_card" or payment_method == "debit_card":
print("Payment method accepted")
else:
print("Payment method not supported")
# Emergency access
user_role = "guest"
emergency_code = "EMERGENCY123"
entered_code = "EMERGENCY123"
if user_role == "admin" or entered_code == emergency_code:
print("Access granted!")
else:
print("Access denied!")
# Negating conditions
is_logged_in = False
if not is_logged_in:
print("Please log in to continue")
else:
print("Welcome back!")
# Checking for empty values
user_input = ""
if not user_input:
print("Input cannot be empty!")
else:
print(f"You entered: {user_input}")
# Inverting boolean conditions
is_weekend = False
is_holiday = False
if not (is_weekend or is_holiday):
print("It's a regular working day")
else:
print("Enjoy your time off!")
# Complex logical expressions
age = 25
income = 50000
credit_score = 720
has_job = True
# Loan approval logic
if (age >= 18 and age <= 65) and (income >= 30000 or has_job) and credit_score >= 650:
print("Loan approved!")
print("Congratulations on your approval!")
elif credit_score < 650:
print("Loan denied: Credit score too low")
elif income < 30000 and not has_job:
print("Loan denied: Insufficient income")
else:
print("Loan denied: Age requirement not met")
# Event ticket pricing
age = 16
is_student = True
is_senior = False
is_member = False
if age < 12:
ticket_price = 0 # Free for children
elif (age >= 12 and age < 18) or is_student:
ticket_price = 10 # Student discount
elif age >= 65 or is_senior:
ticket_price = 12 # Senior discount
elif is_member:
ticket_price = 15 # Member discount
else:
ticket_price = 20 # Regular price
print(f"Your ticket price: ${ticket_price}")
You can place if statements inside other if statements for more complex decision making.
# Basic nested if
weather = "sunny"
temperature = 75
if weather == "sunny":
print("It's a sunny day!")
if temperature > 80:
print("Perfect for swimming!")
elif temperature > 60:
print("Great for a picnic!")
else:
print("A bit cool, but still nice!")
else:
print("Not sunny today.")
# User authentication with multiple levels
username = "admin"
password = "secret123"
two_factor_code = "123456"
if username == "admin":
print("Username verified")
if password == "secret123":
print("Password verified")
if two_factor_code == "123456":
print("Two-factor authentication successful")
print("Full access granted!")
else:
print("Invalid two-factor code")
else:
print("Invalid password")
else:
print("Invalid username")
# Grade calculation with bonus points
base_score = 87
attendance_rate = 95
extra_credit = True
if base_score >= 60: # Passing grade
print("Base score is passing")
if attendance_rate >= 90:
print("Excellent attendance!")
base_score += 2 # Attendance bonus
if extra_credit:
print("Extra credit completed!")
base_score += 3 # Extra credit bonus
if base_score >= 90:
final_grade = "A"
elif base_score >= 80:
final_grade = "B"
elif base_score >= 70:
final_grade = "C"
else:
final_grade = "D"
else:
final_grade = "F"
print(f"Final score: {base_score}")
print(f"Final grade: {final_grade}")
# Check if value exists in a collection
favorite_color = "blue"
available_colors = ["red", "blue", "green", "yellow", "purple"]
if favorite_color in available_colors:
print(f"{favorite_color} is available!")
else:
print(f"Sorry, {favorite_color} is not available.")
# Day of week checking
today = "Friday"
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
weekends = ["Saturday", "Sunday"]
if today in weekdays:
print("It's a weekday - time to work!")
elif today in weekends:
print("It's the weekend - time to relax!")
# Valid file extensions
filename = "document.pdf"
allowed_extensions = [".txt", ".pdf", ".doc", ".docx"]
file_extension = filename[filename.rfind("."):]
if file_extension in allowed_extensions:
print("File type is allowed")
else:
print("File type not supported")
# Check if substring exists in string
email = "user@example.com"
if "@" in email and "." in email:
print("Email format appears valid")
else:
print("Invalid email format")
# Checking for prohibited words
comment = "This is a great product!"
prohibited_words = ["spam", "fake", "scam", "terrible"]
contains_prohibited = False
for word in prohibited_words:
if word in comment.lower():
contains_prohibited = True
break
if contains_prohibited:
print("Comment contains prohibited content")
else:
print("Comment approved")
# More elegant way using any()
if any(word in comment.lower() for word in prohibited_words):
print("Comment flagged for review")
else:
print("Comment looks good")
Python provides a concise way to write simple if-else statements in one line.
# Basic conditional expression
age = 17
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
# Comparison with regular if-else
# Regular way
if age >= 18:
status = "adult"
else:
status = "minor"
# Conditional expression way
status = "adult" if age >= 18 else "minor"
# More examples
temperature = 85
clothing = "light clothes" if temperature > 75 else "warm clothes"
print(f"Wear: {clothing}")
score = 92
grade = "Pass" if score >= 60 else "Fail"
print(f"Result: {grade}")
# Using in calculations
price = 100
discount = 0.1 if price > 50 else 0.05
final_price = price * (1 - discount)
print(f"Final price: ${final_price:.2f}")
# Nested conditional expressions (use sparingly)
grade = 85
letter = "A" if grade >= 90 else ("B" if grade >= 80 else "C")
print(f"Letter grade: {letter}")
def simple_calculator():
"""A basic calculator with conditional logic."""
print("=== Simple Calculator ===")
try:
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == "+":
result = num1 + num2
print(f"{num1} + {num2} = {result}")
elif operator == "-":
result = num1 - num2
print(f"{num1} - {num2} = {result}")
elif operator == "*":
result = num1 * num2
print(f"{num1} * {num2} = {result}")
elif operator == "/":
if num2 != 0:
result = num1 / num2
print(f"{num1} / {num2} = {result}")
else:
print("Error: Cannot divide by zero!")
else:
print("Error: Invalid operator!")
except ValueError:
print("Error: Please enter valid numbers!")
simple_calculator()
def calculate_letter_grade(score):
"""Calculate letter grade based on numeric score."""
if score >= 97:
return "A+"
elif score >= 93:
return "A"
elif score >= 90:
return "A-"
elif score >= 87:
return "B+"
elif score >= 83:
return "B"
elif score >= 80:
return "B-"
elif score >= 77:
return "C+"
elif score >= 73:
return "C"
elif score >= 70:
return "C-"
elif score >= 67:
return "D+"
elif score >= 65:
return "D"
else:
return "F"
def process_student_grades():
"""Process multiple student grades with detailed feedback."""
print("=== Student Grade Processor ===")
while True:
student_name = input("Enter student name (or 'quit' to exit): ")
if student_name.lower() == 'quit':
break
try:
score = float(input(f"Enter {student_name}'s score (0-100): "))
if score < 0 or score > 100:
print("Error: Score must be between 0 and 100!")
continue
letter_grade = calculate_letter_grade(score)
# Determine performance level
if score >= 90:
performance = "Excellent"
message = "Outstanding work!"
elif score >= 80:
performance = "Good"
message = "Well done!"
elif score >= 70:
performance = "Satisfactory"
message = "Keep up the effort!"
elif score >= 60:
performance = "Needs Improvement"
message = "Consider additional study."
else:
performance = "Failing"
message = "Please seek help immediately."
# Display results
print(f"\n--- Results for {student_name} ---")
print(f"Score: {score:.1f}")
print(f"Letter Grade: {letter_grade}")
print(f"Performance: {performance}")
print(f"Comment: {message}")
print("-" * 30)
except ValueError:
print("Error: Please enter a valid number!")
process_student_grades()
def calculate_shopping_discount():
"""Calculate discount based on various criteria."""
print("=== Shopping Discount Calculator ===")
try:
# Get customer information
total_amount = float(input("Enter total purchase amount: $"))
is_member = input("Are you a member? (yes/no): ").lower() == "yes"
customer_age = int(input("Enter your age: "))
is_first_time = input("Is this your first purchase? (yes/no): ").lower() == "yes"
# Initialize discount
discount_percentage = 0
discount_reasons = []
# Apply various discounts
if total_amount >= 200:
discount_percentage += 15
discount_reasons.append("Large purchase discount (15%)")
elif total_amount >= 100:
discount_percentage += 10
discount_reasons.append("Medium purchase discount (10%)")
elif total_amount >= 50:
discount_percentage += 5
discount_reasons.append("Small purchase discount (5%)")
if is_member:
discount_percentage += 10
discount_reasons.append("Member discount (10%)")
if customer_age >= 65:
discount_percentage += 5
discount_reasons.append("Senior citizen discount (5%)")
elif customer_age < 18:
discount_percentage += 3
discount_reasons.append("Student discount (3%)")
if is_first_time:
discount_percentage += 5
discount_reasons.append("First-time customer discount (5%)")
# Cap maximum discount at 40%
if discount_percentage > 40:
discount_percentage = 40
discount_reasons.append("(Maximum discount applied: 40%)")
# Calculate final amounts
discount_amount = total_amount * (discount_percentage / 100)
final_amount = total_amount - discount_amount
# Display results
print(f"\n=== Discount Summary ===")
print(f"Original Amount: ${total_amount:.2f}")
if discount_percentage > 0:
print(f"Total Discount: {discount_percentage}%")
print("Discount Details:")
for reason in discount_reasons:
print(f" • {reason}")
print(f"Discount Amount: ${discount_amount:.2f}")
print(f"Final Amount: ${final_amount:.2f}")
print(f"You saved: ${discount_amount:.2f}!")
else:
print("No discounts available for this purchase.")
print(f"Amount to pay: ${total_amount:.2f}")
except ValueError:
print("Error: Please enter valid numbers!")
calculate_shopping_discount()
# Complex condition - hard to read
if user.age >= 18 and user.has_valid_id and user.account_balance >= 100 and not user.is_suspended and user.verification_status == "verified":
process_transaction()
# Better - break into readable parts
is_adult = user.age >= 18
has_valid_documents = user.has_valid_id
has_sufficient_funds = user.account_balance >= 100
is_account_active = not user.is_suspended
is_verified = user.verification_status == "verified"
if is_adult and has_valid_documents and has_sufficient_funds and is_account_active and is_verified:
process_transaction()
# Even better - use a function
def can_process_transaction(user):
"""Check if user meets all requirements for transaction."""
return (user.age >= 18 and
user.has_valid_id and
user.account_balance >= 100 and
not user.is_suspended and
user.verification_status == "verified")
if can_process_transaction(user):
process_transaction()
# Deep nesting - harder to follow
def process_user_request(user, request):
if user is not None:
if user.is_authenticated:
if user.has_permission(request.action):
if request.is_valid():
return process_request(request)
else:
return "Invalid request"
else:
return "Permission denied"
else:
return "Authentication required"
else:
return "User not found"
# Better - early returns
def process_user_request(user, request):
if user is None:
return "User not found"
if not user.is_authenticated:
return "Authentication required"
if not user.has_permission(request.action):
return "Permission denied"
if not request.is_valid():
return "Invalid request"
return process_request(request)
Conditional statements are essential for creating dynamic, responsive programs:
Key Concepts:
- if statements execute code when conditions are true
- elif statements check multiple conditions in sequence
- else statements provide fallback actions
- Logical operators (and, or, not) combine conditions
- Comparison operators (==, !=, <, >, <=, >=) compare values
- Membership testing (in, not in) checks for values in collections
Best Practices:
- Keep conditions simple and readable
- Use descriptive variable names for complex conditions
- Avoid deep nesting with early returns
- Use conditional expressions for simple cases
- Test edge cases and invalid inputs
- Comment complex logical expressions
Common Patterns:
- Input validation and error handling
- User authentication and authorization
- Business logic and rule enforcement
- Data categorization and classification
- Menu systems and user interfaces
Mastering conditional statements will enable you to create programs that can make intelligent decisions and respond appropriately to different situations!