Developer Tools

Python if, elif, else: Conditional Statements Explained (With Examples)

Learn Python if, else, and elif statements with practical examples. Master conditional logic and control flow in this beginner-friendly Python tutorial.

By Inventive HQ Team

In Python, if runs a block of code when its condition is True, elif checks another condition only when every preceding condition was False, and else runs when nothing above matched — so an if/elif/else chain follows exactly one path. The critical detail that trips up newcomers from other languages: Python spells "else if" as the single keyword elif, and it uses 4-space indentation instead of curly braces to mark each block. Writing else if in Python raises a SyntaxError.

That's the summary an AI overview gives you. What it can't hand you is the working mental model — how truthiness lets if my_list: stand in for a comparison, when a ternary or a match/case reads better than a chain, and the five mistakes that turn a five-line conditional into a silent bug. This guide covers all of it, with runnable examples you can paste into any Python 3 REPL.

age = 20

if age < 13:
    print("Child")
elif age < 18:      # checked only because age < 13 was False
    print("Teenager")
else:               # runs when no condition above matched
    print("Adult")
# Output: Adult

if / elif / else at a glance

ConstructSyntaxWhen it runs
ifif cond:Always evaluated first; its block runs when cond is truthy.
elifelif cond:Only when every if/elif above it was False; runs the first one that's True.
elseelse:Only when no if/elif in the chain matched. Optional; at most one per chain.
Ternarya if cond else bAn expression, not a block — returns a when cond is truthy, else b. No elif.
match/casematch x: + case pattern:Python 3.10+. Dispatches on the value or structure of x; case _: is the fallback.

The animated diagram below traces how execution falls through a chain: each condition is tested top-to-bottom, the first True branch runs, and everything after it is skipped.

Python if / elif / else decision flow Execution enters at the if test and falls down the chain. The first condition that is True runs its block and exits; if none match, the else block runs. How a conditional chain is evaluated if age < 13: tested first True print("Child") elif age < 18: only if above was False True print("Teenager") else: nothing matched print("Adult")

False False

Note: Python uses elif, not else if, and relies on indentation (4 spaces) rather than braces to define each block. The rest of this guide breaks down each keyword with examples, then covers logical operators, truthiness, nesting, one-line (ternary) conditionals, match/case (Python 3.10+), and common mistakes.

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 True
  • elif - 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:

OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater than or equal tox >= 5
<=Less than or equal tox <= 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!
Advertisement

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).

match / case (Python 3.10+)

Python 3.10 introduced match/case (structural pattern matching, PEP 634). It is often described as Python's "switch statement," but it does more: it dispatches on the structure of a value, not just its equality. The subject after match is evaluated once, then each case is tried top-to-bottom, running the first pattern that matches. The wildcard case _: is the catch-all fallback (the equivalent of else).

Syntax

match subject:
    case pattern1:
        # runs if subject matches pattern1
    case pattern2:
        # runs if subject matches pattern2
    case _:
        # fallback when nothing else matches

Example: dispatching on a value

def describe_status(code):
    match code:
        case 200:
            return "OK"
        case 301 | 302:          # the | matches either value
            return "Redirect"
        case 404:
            return "Not Found"
        case _:
            return "Unknown status"

print(describe_status(302))   # Output: Redirect
print(describe_status(500))   # Output: Unknown status

Example: matching structure (where match beats elif)

Where match/case truly shines is destructuring — checking a value's shape and pulling out its parts in one step:

def move(command):
    match command.split():
        case ["go", direction]:
            return f"Moving {direction}"
        case ["pick", "up", item]:
            return f"Picking up {item}"
        case _:
            return "Unknown command"

print(move("go north"))      # Output: Moving north
print(move("pick up key"))   # Output: Picking up key

When to use it: Reach for match/case when you are branching on the shape of structured data — parsing commands, handling API responses, or dispatching on types. For simple true/false checks or one or two branches, a plain if/elif chain is clearer. And remember it requires Python 3.10 or newer — on older interpreters it raises a SyntaxError.

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:

  • None
  • False
  • 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:

  1. if - Executes code when a condition is True
  2. elif - Checks additional conditions sequentially (only if previous conditions were False)
  3. else - Provides a fallback when all conditions are False
  4. Use comparison operators (==, !=, >, <, >=, <=) to create conditions
  5. Combine conditions with logical operators (and, or, not)
  6. Nested if statements allow complex decision trees
  7. Ternary expressions provide compact one-line if-else syntax
  8. 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!

Frequently Asked Questions

Why does Python use elif instead of else if?

Python uses the single keyword elif rather than the two-word else if found in C, Java, or JavaScript. It is purely a syntax choice made to keep conditional chains compact and to avoid the deepening indentation that a nested else { if } would create. Writing else if in Python is a SyntaxError unless you actually intend a nested if inside an else block.

What is the difference between if and elif in Python?

if starts a new conditional check, while elif (short for else if) checks an additional condition only if every preceding if and elif in the same chain was False. Once any condition is True, Python runs that block and skips the remaining elif and else blocks.

Do I need an else statement in Python?

No, the else statement is optional. You can use an if on its own, or if with one or more elif branches, without an else. The else block runs only when all preceding conditions are False, so add it when you need a guaranteed fallback path.

Can I have multiple if statements instead of elif?

Yes, but they behave differently. Separate if statements are each evaluated independently, so more than one block can run. An if-elif chain is a single decision where only the first True branch executes. Use elif for mutually exclusive cases.

How do I write multiple conditions in an if statement?

Combine conditions with the logical operators and (both must be True), or (at least one must be True), and not (negates a condition). Example: if age >= 18 and has_license. Wrap mixed and/or logic in parentheses to make precedence explicit.

How do I write an if statement in one line in Python?

Use a ternary conditional expression: result = 'adult' if age >= 18 else 'minor'. It returns one of two values based on the condition. Ternary expressions handle only a single if-else and cannot include elif branches.

What are truthy and falsy values in Python?

In a boolean context Python treats certain values as False without any comparison: None, False, zero (0, 0.0, 0j), and empty containers ('', [], (), {}, set()). Everything else is truthy. That is why if my_list: is the idiomatic way to check that a list is not empty.

When should I use match-case instead of if-elif in Python?

match-case (added in Python 3.10) is best when you are branching on the shape or structure of data, such as parsing commands, dispatching on types, or destructuring tuples and dictionaries. For simple true/false checks or a couple of branches, an ordinary if-elif chain is clearer.

PythonProgrammingConditional StatementsPython 3Control FlowSoftware DevelopmentPython If ElsePython ElifElse If Python