Concepts / Understand Boolean Expressions

Understand Boolean Expressions

The most useful tracing question is: What is the condition's Boolean result? Once that result is known, the executing branch is determined.

  • 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

Many programs need to choose between two alternatives. An if-else statement makes this choice by using a condition. If the condition is true, one block of code runs. If the condition is false, the other block runs. This is called alternative execution because the program follows one of two possible execution paths.

if-else statementconditionTrue or Falseif blockcondition is Truenext statementelse blockcondition is FalseevaluateTrueFalsethen continuethen continue
What happens next when the condition evaluates to true or false?

Evaluate Before Executing

Python does not choose a branch at random and does not execute both blocks. It first evaluates the condition. A condition is a Boolean expression, so its result is either True or False. A True result sends execution into the block under if. A False result sends execution into the block under else. After the selected block finishes, execution continues with the statement that follows the if-else statement.

input or comparisonBoolean resultTrue or Falseif blockTrueelse blockFalseevaluateTrueFalse
How does a Boolean expression change an input or comparison into a true or false value?
Key point

The most useful tracing question is: What is the condition's Boolean result? Once that result is known, the executing branch is determined.

Writing the Two Blocks

Definition

An if-else statement has two code blocks. The first follows if and runs when the condition is true. The second follows else and runs when the condition is false.

The structure is ordered: write if, then the condition, then a colon. Put the first block at the required indentation. Next write else followed by a colon, and put the second block at its indentation. The colons and indentation show Python where the statement and each block begin.

ifstarts the conditionif blockindented codeelsealternative branchelse blockindented codeconditionproduces True or False:ends the else line:ends the condition linefollowed byfollowed byopensfollowed byfollowed byopens
Which condition, colon, indentation level, and code block belong to each part of an if-else statement?

Tracing an Even-or-Odd Decision

Worked example

Choosing a Branch for an Input

Trace an if-else statement that classifies an input as even or odd.

  1. 1
    Start with the input

    Use the given number as the input for the even-or-odd example.

  2. 2
    Evaluate the condition

    Determine whether the condition about the input is True or False before considering either block.

  3. 3
    Choose one branch

    If the condition is True, follow the if block. If the condition is False, skip the if block and follow the else block.

  4. 4
    Continue afterward

    Exactly one block has executed, so tracing continues with the statement after the if-else statement.

Result

The condition determines the result: a True condition selects the if block, and a False condition selects the else block.

input valueTruecondition resultif blockexecutesFalsecondition resultelse blockexecutescondition evaluatescondition evaluatesselectselect
How does a specific input map to either the if branch or the else branch?

The important tracing habit is to separate the stages. First identify the input. Next evaluate the condition. Finally follow only the branch that matches the result. Do not trace statements from the skipped branch as if they had executed.

Common Branching Mistakes

  • Common mistake

    Leaving out the colon after the condition.

    What it looks like

    The condition is written without the colon that should end its line.

    Why it fails

    The required if-else structure includes a colon after the condition.

    Do this instead

    End the condition line with a colon.

  • Common mistake

    Leaving out the colon after else.

    What it looks like

    The alternative branch is written as else without a colon.

    Why it fails

    The else part also requires a colon before its block.

    Do this instead

    Write else followed by a colon.

  • Common mistake

    Using incorrect indentation for a block.

    What it looks like

    Statements intended to belong to the if or else block are not placed at the required indentation.

    Why it fails

    Proper indentation identifies the code belonging to each block.

    Do this instead

    Keep the statements in each block properly indented.

  • Common mistake

    Assuming both blocks execute.

    What it looks like

    Tracing statements from the if block and the else block for one condition.

    Why it fails

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

    Do this instead

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

  • Common mistake

    Choosing a branch before evaluating the condition.

    What it looks like

    Following the if block simply because it appears first.

    Why it fails

    Python evaluates the condition before selecting a branch.

    Do this instead

    Record whether the condition is True or False before tracing execution.

Branch Selection Practice

What do you think happens?

A condition in an if-else statement evaluates to False. Which block executes?

  • Only the if block

  • Only the else block

  • Both blocks

  • Neither block

Reveal answer
Answer:

Only the else block

Python evaluates the condition first. When the result is False, it skips the if block and executes the else block.

EASY

For an if-else statement whose condition evaluates to True, describe the execution path in order. Include the condition evaluation, the selected block, the skipped block, and what happens after the selected block finishes.

Hints
  • Begin by naming the Boolean result.
  • Remember that the block under else is skipped when the condition is True.
  • Finish by stating that execution continues after the if-else statement.
MEDIUM

Inspect the structure of an if-else statement and list the four syntax features you should check: the condition, the colon after the condition, the colon after else, and the indentation of both blocks.

Hints
  • Check the line beginning with if.
  • Check the line beginning with else.
  • Check the indentation beneath each branch.

Key Takeaways

  1. 1
    Alternative execution uses if-else to choose between two code blocks.
  2. 2
    Python evaluates the condition before selecting a branch.
  3. 3
    A True condition executes the if block, while a False condition executes the else block.
  4. 4
    Exactly one block executes for each if-else statement.
  5. 5
    Correct syntax requires a colon after the condition and after else, along with proper indentation for each block.

At a glance

  • An if-else statement provides two alternative execution paths.
  • The condition is a Boolean expression that evaluates to True or False.
  • Trace the statement by evaluating the condition first and then following the matching branch.
  • The if block runs for True; the else block runs for False.
  • Colons and proper indentation are required parts of the structure.

Related concepts

More concepts starting with U