Python Conditional Statements - Complete Guide

Understanding Conditional Statements

Conditional statements in Python allow your program to make decisions based on certain conditions. They direct the flow of execution by evaluating conditions as either true or false.

Python supports several conditional constructs, primarily:

  • if statements
  • if-else statements
  • if-elif-else statements
  • Nested conditions
  • Conditional expressions (ternary operators)
# Basic conditional structure
temperature = 22

if temperature > 30:
    print("It's hot outside!")
elif temperature > 20:
    print("It's a nice day!")
else:
    print("It's cold outside!")

Simple if Statement

The simplest form of a conditional statement is the if statement. It executes a block of code only when the specified condition evaluates to True.

# Basic if statement
age = 18

if age >= 18:
    print("You are an adult.")
    print("You can vote.")

# If statement with multiple conditions (using logical operators)
age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive.")

# If statement with a single line of code
if age > 65: print("Senior citizen discount applied.")

Truthy and Falsy Values

In Python, all values have an inherent boolean value (true or false). Understanding "truthy" and "falsy" values is essential for writing effective conditions.

# Falsy values in Python
if False:     print("This won't print")
if None:      print("This won't print")
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 set():     print("This won't print")

# Truthy values in Python
if True:      print("This will print")
if 42:        print("This will print")
if "hello":   print("This will print")
if [1, 2, 3]: print("This will print")

if-else Statement

The if-else statement provides an alternative execution path when the condition is False.

# Basic if-else statement
age = 15

if age >= 18:
    print("You can vote!")
else:
    print("You cannot vote yet.")
    years_left = 18 - age
    print(f"Wait {years_left} more years.")

if-elif-else Statement

When you need to check multiple conditions, the if-elif-else chain allows you to evaluate them in sequence until one is true.

# Multiple conditions with if-elif-else
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: {grade}")

# you can have multiple elif blocks
day = "Monday"

if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
elif day == "Monday":
    print("Start of the workweek.")
elif day == "Friday":
    print("End of the workweek!")
else:
    print("It's a regular workday.")

Important Features

  • Only the first true condition's block will execute
  • The else block is optional
  • You can have as many elif blocks as needed

Nested Conditional Statements

You can place conditional statements inside other conditional statements to create more complex decision trees.

# Nested conditional statements
age = 25
income = 50000

if age >= 18:
    print("Adult")
    
    if income < 30000:
        tax_rate = 0.15
    elif income < 60000:
        tax_rate = 0.2
    else:
        tax_rate = 0.25
    
    print(f"Tax rate: {tax_rate * 100}%")
else:
    print("Minor - no income tax")

Best Practices

  • Avoid deeply nested conditions (more than 2-3 levels) when possible
  • Consider refactoring complex nested conditions into separate functions
  • Use clear indentation to maintain readability

Conditional Expressions (Ternary Operator)

Python offers a compact way to write conditional statements in a single line using conditional expressions, also known as the ternary operator.

# Basic ternary operator
age = 20
status = "Adult" if age >= 18 else "Minor"

# Equivalent to:
# if age >= 18:
#     status = "Adult"
# else:
#     status = "Minor"

# Nested ternary
age = 65
category = "Senior" if age >= 65 else ("Adult" if age >= 18 else "Minor")

# Using ternary in a string
age = 15
print(f"You are {'eligible' if age >= 18 else 'not eligible'} to vote.")

Advanced Conditional Techniques

1. Using match-case Statement (Python 3.10+)

For Python 3.10 and above, the match-case statement provides pattern matching capabilities.

# Basic match-case (Python 3.10+)
status_code = 404

match status_code:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case 500:
        print("Server Error")
    case _:
        print("Unknown Code")

# Pattern matching with guards
point = (3, 4)

match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y-axis at {y}")
    case (x, 0):
        print(f"X-axis at {x}")
    case (x, y) if x == y:
        print(f"Diagonal at {x}")
    case (x, y):
        print(f"Point at {x}, {y}")

2. Conditional Assignment with Short-Circuit Evaluation

# Using 'or' for default values
name = user_name or "Guest"  # If user_name is falsy, use "Guest"

# Using 'and' for conditional execution
is_admin and print("Admin panel access granted")  # Only prints if is_admin is True

# Combining 'and'/'or'
result = value if condition else default
# Can be rewritten as
result = condition and value or default  # Be careful with this pattern!

3. Dictionary-Based Dispatch

Instead of long if-elif chains, sometimes a dictionary dispatch table is cleaner and more efficient.

# Instead of:
# if day == "Monday":
#     schedule = "Meeting"
# elif day == "Tuesday":
#     schedule = "Project"
# # ... etc

# Use dictionary-based dispatch:
day_schedule = {
    "Monday": "Meeting",
    "Tuesday": "Project",
    "Wednesday": "Development",
    "Thursday": "Testing",
    "Friday": "Planning"
}

schedule = day_schedule.get(day, "No schedule found")

# Function dispatch table
def handle_login():
    return "Login page"

def handle_logout():
    return "Logout page"

def handle_profile():
    return "Profile page"

def handle_error():
    return "Error page"

handlers = {
    "/login": handle_login,
    "/logout": handle_logout,
    "/profile": handle_profile
}

path = "/login"
response = handlers.get(path, handle_error)()

Best Practices and Common Pitfalls

Best Practices

  • Keep conditions simple and readable
  • Use descriptive variable names to make conditions self-explanatory
  • For complex conditions, store parts in named variables
  • Prefer positive conditions when possible
  • Be careful with equality comparisons (== vs is)
# Complex condition - hard to read
if age >= 18 and (income > 30000 or has_scholarship) and not is_suspended:
    grant_admission()

# Better approach - break it down
is_adult = age >= 18
meets_financial_requirements = income > 30000 or has_scholarship
is_in_good_standing = not is_suspended

if is_adult and meets_financial_requirements and is_in_good_standing:
    grant_admission()

Common Pitfalls

# Misusing '==' and 'is'
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True (values are equal)
print(a is b)  # False (different objects)

# Using assignment instead of comparison
# This is a bug - assigns 10 to x and always evaluates to True
# if x = 10:  # SyntaxError in Python
#     print("x is 10")

# Forgetting parentheses in complex conditions
if a > b or c and d:  # Evaluated as: (a > b) or (c and d)
    print("Condition met")

# Checking None with equality
# Not ideal
if x == None:
    print("x is None")

# Better
if x is None:
    print("x is None")

Practice Exercises

Exercise 1: Grade Calculator

# Write a program that takes a student's score (0-100)
# and prints their letter grade according to:
# A: 90-100
# B: 80-89
# C: 70-79
# D: 60-69
# F: 0-59

score = 85

# Your code here

Exercise 2: Leap Year Checker

# Create a program that checks if a year is a leap year.
# A leap year is:
# - Divisible by 4
# - Not divisible by 100 unless it's also divisible by 400

year = 2024

# Your code here

Exercise 3: BMI Calculator with Categories

# Calculate BMI (weight in kg / height in meters squared)
# and classify it according to:
# - Underweight: < 18.5
# - Normal: 18.5 - 24.9
# - Overweight: 25 - 29.9
# - Obese: >= 30

weight = 70  # kg
height = 1.75  # meters

# Your code here