Concepts / if-else Statements

if-else Statements

The if statement checks a condition and executes indented code only if that condition is true.

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

Choosing a Path

Programs often need to respond differently depending on a condition. An if-else statement provides two alternative execution paths: one block runs when the condition is true, and the other block runs when the condition is false. Learning to trace those paths lets you predict what a program will do before it runs and helps you locate unexpected behavior.

ConditionTrue or Falseif blockNext statementelse blockTrueFalsethenthen
Which branch executes after Python evaluates the condition, and which branch is skipped?

First Trace

What do you think happens?

Suppose the condition evaluates to True. Which block executes: the if block, the else block, or both?

  • The if block

  • The else block

  • Both blocks

Reveal answer
Answer:

The if block

Python evaluates the condition first. When it is True, Python executes the indented code under if and skips the else block. Exactly one block executes.

Code walkthrough
temperature = 25

if temperature > 20:
    print("Warm")
else:
    print("Cool")
  1. 1
    Python evaluates the condition temperature > 20.
  2. 2
    The condition is True because 25 is greater than 20.
  3. 3
    Python executes the indented if block and prints Warm.
  4. 4
    Python skips the else block.
  5. 5
    The resulting output is Warm.
Output
Warm
Conditiontemperature > 20TrueWarmFalseCoolevaluates toselects ifotherwiseselects else
How does one boolean result select one of two alternative execution paths?

Python Structure

An if-else statement contains a condition and two indented code blocks. Write if, then the condition, followed by a colon. The statements belonging to the if branch must be indented. Write else followed by a colon, then indent the statements belonging to the else branch. The colon marks the start of each block, while indentation shows which statements belong to that block.

python
ifstarts a conditionif statementindentedelsealternative branchelse statementindentedconditionboolean result:opens else block:opens if blockfollowed byfollowed bycontainsfollowed byfollowed bycontains
Which parts identify the condition, the block boundaries, and the two alternative code blocks?

Alternative Execution

Definition

Alternative execution uses if-else to run one of two code blocks based on whether a condition is true or false. Python evaluates the condition first. If the result is True, it executes the if block and skips the else block. If the result is False, it skips the if block and executes the else block.

Condition resultBlock that executesBlock that is skipped
Trueif blockelse block
Falseelse blockif block

An if-else statement selects exactly one of its two blocks.

Use if-else when both outcomes need an explicit response. The if block describes what should happen when the condition is true, and the else block describes the alternative when it is false. Because exactly one block executes, an if-else statement gives the program a complete two-way choice for that condition.

Second Trace

What do you think happens?

For number = 7, which message will execute in this even-or-odd decision?

  • Even

  • Odd

  • Both messages

Reveal answer
Answer:

Odd

The condition for the even case is false for 7, so Python skips the if block and executes the else block. The two branches do not both execute.

Code walkthrough
number = 7

if number % 2 == 0:
    print("Even")
else:
    print("Odd")
  1. 1
    Python evaluates the condition number % 2 == 0.
  2. 2
    For number equal to 7, the condition is False.
  3. 3
    Python skips the indented if block, so Even is not printed.
  4. 4
    Python executes the indented else block and prints Odd.
  5. 5
    The resulting output is Odd.
Output
Odd
7 is evenFalseEvenskippedNext statementOddexecutesFalseselects elsethen
How does execution proceed when the condition evaluates to False?

Debugging Branches

Debugging an if-else statement means tracing the program from the condition onward. First determine whether the condition is True or False. Then check that the selected block is the one you expected, that its statements are indented as part of the block, and that the other block is skipped. The point where the actual path differs from the expected path identifies where to investigate.

  • Common mistake

    Leaving out the colon after the condition.

    What it looks like

    if score > 50

    Why it fails

    The syntax requires a colon after the condition.

    Do this instead
    if score > 50:
  • Common mistake

    Leaving out the colon after else.

    What it looks like

    else

    Why it fails

    The else branch also requires a colon before its indented block.

    Do this instead
    else:
  • Common mistake

    Failing to indent the statements in a branch.

    What it looks like
    if score > 50:
    print("Pass")
    Why it fails

    Indentation identifies the code belonging to the if block.

    Do this instead
    if score > 50:
        print("Pass")
  • Common mistake

    Expecting both branches to execute.

    What it looks like

    A True condition does not execute both the if and else blocks.

    Why it fails

    An if-else statement executes exactly one block: the if block for True or the else block for False.

    Do this instead

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

  • Common mistake

    Tracing the branch before evaluating the condition.

    What it looks like

    Assuming the if block runs without deciding whether the condition is True.

    Why it fails

    Python evaluates the condition before selecting an execution path.

    Do this instead

    Write down the condition's boolean result first, then identify the selected block.

ConditionTrueif blockConditionFalseelse blockexpected pathactual path
At what point does the actual execution path differ from the expected path?

Branch Practice

EASY

Trace this statement for value = 3. Identify the condition's truth value, name the block that executes, and state which block is skipped.

Hints
  • Evaluate value > 5 before choosing a branch.
  • A False condition selects the else block.
  • Exactly one block executes.
python
Worked example

Tracing value = 3

Determine the execution path for the if-else statement using value = 3.

  1. 1
    Evaluate

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

  2. 2
    Select

    The False result selects the else block.

  3. 3
    Skip

    The if block is skipped, so Large is not printed.

  4. 4
    Execute

    The else block executes and prints Small.

Result

The output is Small. Exactly one branch executes.

Key Takeaways

  1. 1
    An if-else statement evaluates a condition before selecting an execution path.
  2. 2
    A True condition runs the indented if block and skips the else block.
  3. 3
    A False condition skips the if block and runs the indented else block.
  4. 4
    A colon is required after the condition and after else, and indentation identifies each block.
  5. 5
    To debug an unexpected result, evaluate the condition first and trace the selected branch step by step.

At a glance

  • An if-else statement provides two alternative execution paths.
  • Python evaluates the condition first and executes exactly one branch.
  • The if branch runs for True; the else branch runs for False.
  • Correct colons and indentation are essential to the syntax.
  • Tracing the condition and selected branch is the central debugging technique.

Related concepts

More concepts starting with I