Concepts / Write if-elif-else Statements

Write if-elif-else Statements

Alternative execution uses if-else to run one of two code blocks based on whether a condition is true or false.

  • 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…

One Decision, Two Paths

Programs often need to choose between two actions. Alternative execution handles this choice: Python evaluates a condition, then runs one code block when the condition is true and another code block when the condition is false. The supplied material establishes this two-branch if-else form as the foundation for understanding alternative execution.

Following the Execution Path

ConditionTrue or FalseTrueif blockexecutesFalseelse blockexecutesevaluates aschooseevaluates aschoose
What happens after Python evaluates the condition?

Tracing means following the decision in order. First, evaluate the condition. If it produces True, follow the if path and execute the indented code under if. Python skips the else block. If the condition produces False, skip the if block and execute the indented code under else. Exactly one of these two blocks runs: never both and never neither.

What do you think happens?

Suppose a condition evaluates to False. Which branch executes?

  • The if block

  • The else block

  • Both blocks

  • Neither block

Reveal answer
Answer:

The else block

Python skips the if block when its condition is False and executes the code under else.

Writing the Branch Structure

python

The structure has four essential parts. Write if, followed by a condition and a colon. Put the first block on the indented lines below it. Then write else followed by a colon, and put the second block on the indented lines below else. The condition is a boolean expression, so it results in either True or False.

ifstarts the decisionconditionboolean expression:ends the headerfirst blockindented codeelsealternative path:ends the headersecond blockindented codefollowed byfollowed bycontainsfollowed byfollowed bycontains
How are the condition, colons, and indented blocks arranged?

Even and Odd Trace

The source material identifies an even-or-odd example as a useful way to trace alternative execution. The following concrete Python version is a generated teaching example that applies the documented if-else rules.

Code walkthrough
number = 8

if number % 2 == 0:
    result = "even"
else:
    result = "odd"

print(result)
  1. 1
    Python evaluates number % 2 == 0.
  2. 2
    For number equal to 8, the condition is true because 8 is divisible by 2.
  3. 3
    Python executes the indented if block and assigns even to result.
  4. 4
    Python skips the else block.
  5. 5
    The program prints even.
  • The input value is 8.
  • The condition checks whether the remainder after division by 2 is 0.
  • The if block assigns even when the condition is true.
  • The else block assigns odd when the condition is false.
  • The selected result is printed.
Output
even
8numberTruenumber % 2 == 0evenif block resultoddelse block skippedevaluateTruenot taken
Given number equal to 8, which branch executes and which branch is skipped?

Mistakes in Branching

  • Common mistake

    Leaving out the colon after the condition.

    What it looks like

    if condition

    Why it fails

    The documented syntax requires a colon after the condition.

    Do this instead

    Write if condition: before the indented first block.

  • Common mistake

    Leaving out the colon after else.

    What it looks like

    else

    Why it fails

    The documented syntax requires a colon after else.

    Do this instead

    Write else: before the indented second block.

  • Common mistake

    Treating the two blocks as if both will execute.

    What it looks like

    Expecting both result assignments to happen.

    Why it fails

    Python executes exactly one block: the if block when the condition is true, or the else block when it is false.

    Do this instead

    Evaluate the condition first, then follow only the matching branch.

  • Common mistake

    Ignoring indentation when identifying a block.

    What it looks like

    Placing a branch statement at the same indentation as the surrounding code.

    Why it fails

    The source requires proper indentation for each block.

    Do this instead

    Place each block's code on indented lines beneath its if or else header.

Best practice

When tracing any documented if-else statement, use a fixed order: identify the condition, decide whether it is True or False, select the matching block, and mark the other block as skipped. This prevents the common mistake of mentally executing both alternatives.

Branch Selection Practice

EASY

Trace the following statement for a value of 3. Which value is assigned to result?

Hints
  • Evaluate the condition before choosing a block.
  • Decide whether 3 is greater than 5.
  • Only one of the two indented blocks executes.
python
Worked example

Tracing value 3

Determine which branch runs when value is 3.

  1. 1
    Evaluate the condition

    The condition value > 5 is false because 3 is not greater than 5.

  2. 2
    Choose the path

    Because the condition is false, Python skips the if block.

  3. 3
    Run the alternative

    Python executes the indented else block and assigns not large to result.

Result

The else block executes, and result receives not large.

Key Takeaways

  1. 1
    Alternative execution chooses between two code blocks according to whether a condition is True or False.
  2. 2
    An if-else statement requires a colon after the condition and after else.
  3. 3
    Each branch is written as a properly indented block.
  4. 4
    Python evaluates the condition first, then executes exactly one branch.
  5. 5
    To trace a statement, determine the condition's result and follow only the corresponding execution path.

At a glance

  • Use alternative execution when one of two code blocks should run.
  • Write the condition and if header with a colon, then indent the first block.
  • Write else followed by a colon, then indent the alternative block.
  • Evaluate the condition before tracing the program's path.
  • Exactly one block executes in the documented if-else form.

Related concepts

More concepts starting with W