Concepts / Conditional Statements (if, elif, else)

Conditional Statements (if, elif, else)

In an if-else structure, exactly one of the two blocks will run. The program never runs both the if-block and the else-block in the same execution.

  • Programming
Interactive lab

Try it: if / elif / else

How Python tests if / elif conditions from the top, runs only the first true branch, and how and / or stop evaluating as soon as the answer is known (short-circuiting).

How it works

  1. Python evaluates the if condition first.
  2. If it is False, it tries each elif in order; the first True one runs and the rest are skipped without being tested.
  3. If none is True, the else branch runs.
  4. and stops at the first False, or stops at the first True — the right side may never be evaluated.

Default run (5 steps): score = 84; A = 90, B = 80, C = 70. Python tests the conditions from the top. … print(grade) shows B.

Educational simulation

Loading the simulation…

What Conditionals Do

Every program makes decisions. When you check your email, the program asks: Is there a new message? If yes, it shows a notification. If no, it stays silent. This decision-making is the job of conditional statements. A conditional statement checks whether something is true or false, then runs different code depending on the answer. In Python, we use if, elif, and else to build these decision points into our programs.

In the real world

Imagine a security system at a door. If your ID is valid, the door unlocks. If your ID is invalid, the door stays locked and an alarm sounds. The system doesn't do both—it checks the condition (Is the ID valid?) and then follows one path or the other. Conditional statements work the same way: they evaluate a condition and choose which block of code to run.

The if Statement: Checking a Single Condition

The if statement is the foundation of all conditionals. It checks a condition and runs a block of statements if that condition is true. The block of code that runs is called the if-block. If the condition is false, the if-block is skipped entirely, and the program continues with whatever comes after the if statement.

Definition

The if-block is the set of statements that execute when an if statement's condition evaluates to true. These statements are grouped together through indentation.

python
Output (expected)
You are an adult.
Program continues here.
Walk through it
  1. 1
    age is assigned the value 18
  2. 2
    The condition age >= 18 is evaluated: 18 >= 18 is true
  3. 3
    Because the condition is true, the indented print statement runs
  4. 4
    The program then continues to the next line (not indented), which always runs

What do you think happens?

What will this code print if age is 16 instead of 18?

  • You are an adult. Program continues here.

  • Program continues here.

  • Nothing at all

Reveal answer
Answer:

Program continues here.

When age is 16, the condition age >= 18 is false. The indented print statement inside the if-block is skipped. Only the line outside the if block (not indented) runs, so we see only 'Program continues here.'

Adding an else Clause for the False Case

Often you want to run one block of code if a condition is true and a different block if it is false. This is where the else clause comes in. The else clause is optional—you can write an if statement without it. But when you include else, it provides a fallback: if the condition is false, the else-block runs instead. Only one of the two blocks will ever execute.

Definition

The else-block is the set of statements that execute when an if statement's condition evaluates to false. Like the if-block, the else-block is grouped through indentation.

python
Output (expected)
You are not yet an adult.
Program continues here.
Walk through it
  1. 1
    age is assigned 16
  2. 2
    The condition age >= 18 is evaluated: 16 >= 18 is false
  3. 3
    Because the condition is false, the if-block is skipped
  4. 4
    The else-block runs instead, printing 'You are not yet an adult.'
  5. 5
    The program continues to the next line
Key point

In an if-else structure, exactly one of the two blocks will run. The program never runs both the if-block and the else-block in the same execution.

Handling Multiple Conditions with elif

Sometimes you need to check more than two possibilities. For example, you might want to assign a letter grade based on a test score: A for 90 and above, B for 80 to 89, C for 70 to 79, and so on. You could nest multiple if-else statements, but that creates deep indentation and is hard to read. Instead, use elif (short for else-if). The elif clause lets you chain multiple conditions together in a single, readable structure. You can have as many elif clauses as you need, and they are checked in order from top to bottom. The first condition that is true wins—its block runs, and all the others are skipped. If none of the conditions are true, an optional else clause runs as a final fallback.

Definition

The elif clause combines an else and an if into one statement. It allows you to check a new condition only if the previous condition was false, reducing indentation and improving readability.

python
Output (expected)
Grade: B
Program continues here.
Walk through it
  1. 1
    score is 85
  2. 2
    Check: score >= 90? No, so skip the first if-block
  3. 3
    Check: score >= 80? Yes, so run this elif-block and print 'Grade: B'
  4. 4
    All remaining elif and else clauses are skipped
  5. 5
    The program continues to the next line

Tracing Execution Through a Conditional Chain

To understand how elif chains work, it helps to trace through the execution step by step. Let's walk through a complete example that shows how the program evaluates each condition and decides which block to run.

Worked example

Guessing Game Logic

A number-guessing game checks the player's guess against the secret number (42). If the guess is too high, it says 'Too high!' If the guess is too low, it says 'Too low!' If the guess is correct, it says 'You got it!' Trace the execution when the player guesses 30.

  1. 1
    Set up the values

    secret = 42, guess = 30

  2. 2
    Check the first condition

    Is guess == secret? Is 30 == 42? No, this is false. Skip the first if-block.

  3. 3
    Check the first elif condition

    Is guess > secret? Is 30 > 42? No, this is false. Skip this elif-block.

  4. 4
    Check the second elif condition

    Is guess < secret? Is 30 < 42? Yes, this is true. Run this elif-block.

  5. 5
    Execute the matching block

    Print 'Too low!' and then skip all remaining elif and else clauses.

  6. 6
    Continue

    The program moves to the next statement after the entire if-elif-else chain.

Result

The output is 'Too low!' because the condition guess < secret was the first true condition encountered.

Startguess == secret?Print 'You got it!'Continueguess > secret?Print 'Too high!'guess < secret?Print 'Too low!'Print 'Invalid input'truefalsetruefalsetruefalse
How does the program decide which block to run? Follow the path from top to bottom: each condition is checked in order, and the first true condition determines which block executes.

Syntax Rules: Colons and Indentation

Python uses indentation (spaces or tabs at the start of a line) to group statements into blocks. This is different from many other languages, which use curly braces or keywords. In conditional statements, every line that belongs to an if-block, elif-block, or else-block must be indented by the same amount. The if, elif, and else keywords themselves are not indented—they sit at the same level as each other. Each of these keywords must be followed by a colon (:) at the end of the line.

Key point

The elif and else statements must also have a colon at the end of the logical line followed by their corresponding block of statements with proper indentation.

python
Output (expected)
It is warm.
Enjoy the day.
Done.
Notes on the code
  • if, elif, and else are aligned at the same indentation level
  • Statements inside each block are indented further
  • The colon (:) ends each if, elif, and else line
  • print('Done.') is not indented, so it runs regardless of which block executed

When else and elif Are Optional

A minimal valid if statement requires only the if keyword, a condition, a colon, and an indented block. The elif and else parts are optional. You can write an if statement by itself, and if the condition is false, the program simply skips the block and continues. This is useful when you only need to do something if a condition is true, and there is no alternative action needed.

python
Output (expected)
Welcome, Alice!
Login complete.
Walk through it
  1. 1
    If username is 'alice', the if-block runs and prints 'Welcome, Alice!'
  2. 2
    Then 'Login complete.' always prints
  3. 3
    There is no else clause—we do not need to handle the false case

In this example, if username were 'bob' instead, the if-block would be skipped, and only 'Login complete.' would print. No error occurs—the program runs fine without an else clause.

Common Mistakes

  • Common mistake

    Forgetting the colon after if, elif, or else

    What it looks like
    if age >= 18
        print('Adult')
    Why it fails

    Python requires a colon to mark the end of the condition line. Without it, you get a syntax error and the program will not run.

    Do this instead
    if age >= 18:
        print('Adult')
  • Common mistake

    Incorrect indentation or mixing indentation styles

    What it looks like
    if score > 80:
    print('Pass')
    Why it fails

    The print statement is not indented, so Python thinks it is outside the if-block. The statement will run regardless of the condition, which is not the intended behavior.

    Do this instead
    if score > 80:
        print('Pass')
  • Common mistake

    Using = (assignment) instead of == (comparison) in a condition

    What it looks like
    if age = 18:
        print('Adult')
    Why it fails

    The = operator assigns a value; it does not compare. This causes a syntax error. Use == to check if two values are equal.

    Do this instead
    if age == 18:
        print('Adult')
  • Common mistake

    Checking multiple conditions with and/or incorrectly

    What it looks like
    if score > 80 and < 90:
        print('B grade')
    Why it fails

    The second part '< 90' is incomplete—it lacks a variable to compare. Python does not understand what you are comparing.

    Do this instead
    if score > 80 and score < 90:
        print('B grade')
  • Common mistake

    Assuming elif runs even when the previous if was true

    What it looks like
    if x > 5:
        print('Greater than 5')
    elif x > 3:
        print('Greater than 3')
    Why it fails

    If the first if condition is true, the elif is not checked. Only one block runs in an if-elif-else chain. If x is 10, only 'Greater than 5' prints.

    Do this instead

    Understand that elif only runs if all previous conditions were false. This is the intended behavior—no correction needed, just correct your mental model.

Practical Notes and Best Practices

Practice

MEDIUM

Write a conditional statement that checks a person's age and prints the appropriate message: 'Child' if age is less than 13, 'Teen' if age is 13 to 19, 'Adult' if age is 20 to 64, and 'Senior' if age is 65 or older. Test your code with at least three different ages.

Hints
  • Use if for the first condition and elif for the others.
  • Think about the order: should you check the smallest ages first or the largest?
  • Remember to use >= and < to define the ranges correctly.
MEDIUM

Write a conditional statement that checks if a number is positive, negative, or zero. Print the appropriate message. Then, modify your code to also check if the number is even or odd (if it is not zero) and include that information in the message.

Hints
  • Start with a simple if-elif-else for positive, negative, and zero.
  • To check if a number is even, use the modulo operator: number % 2 == 0.
  • You may need to nest conditions or use multiple if statements.

Summary

Conditional statements are the decision-makers of your programs. The if statement checks a condition and runs a block of code if it is true. The optional else clause provides a fallback block if the condition is false. The elif clause lets you chain multiple conditions together, checking them in order until one is true. Exactly one block in an if-elif-else chain will run (or none, if there is no else and all conditions are false). Always remember the colon after if, elif, and else, and always indent the statements that belong to each block. With these tools, you can write programs that respond differently to different inputs and make intelligent decisions.

At a glance

  • The if statement checks a condition and runs a block of code if the condition is true; the else-block is optional and runs if the condition is false.
  • The elif clause allows you to check multiple conditions in sequence; the first true condition wins, and all others are skipped.
  • Exactly one block in an if-elif-else chain executes, or none if there is no else and all conditions are false.
  • Python uses indentation to group statements into blocks, and every if, elif, and else line must end with a colon.
  • Order matters in elif chains—arrange conditions from most specific to most general to avoid unintended matches.

Related concepts

More concepts starting with C