Concepts / Basic if Statements

Basic if Statements

An if-else statement creates two mutually exclusive branches: one executes if the condition is true, the other if it is 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…

Choosing a Path

Programs often need to respond differently depending on a condition. An if-else statement provides exactly two possible paths: one path runs when the condition is true, and the other runs when the condition is false. These paths are called branches, and the structure is known as alternative execution.

conditiontrue branchfollowing codefalse branchtruefalsethenthen
How does the condition determine which of the two execution paths runs, and why can only one branch execute?

Tracing the Decision

To trace an if-else statement, do not read both branches as though both will run. First evaluate the condition. If it is true, follow the if branch and skip the else branch. If it is false, skip the if branch and follow the else branch. After the selected branch finishes, execution continues with the code after the complete if-else statement.

startevaluate conditionif blockcode afterwardelse blocknexttruefalseskip elseskip if
What happens next as the program evaluates the condition, enters one branch, skips the other, and reaches the code afterward?

What do you think happens?

Suppose the condition is true. Which messages are produced: the message in the if branch, the message in the else branch, or both?

  • The if-branch message only

  • The else-branch message only

  • Both messages

Reveal answer
Answer:

The if-branch message only.

A true condition selects the if branch. The else branch is skipped, so exactly one branch executes.

Writing the Structure

An if-else statement has an if line, a condition, and a colon. The statements belonging to that branch are placed in an indented block. The else line also requires a colon, and its statements form a second consistently indented block. The two blocks represent the alternative branches.

python
ifstarts the true branchconditionvalue to evaluate:ends the if linetrue blockconsistently indentedelsestarts the false branch:ends the else linefalse blockconsistently indented
Where does each part of the intended control flow appear in the syntax?

Reading a Complete Example

Worked example

Selecting One Message

Trace the two possible outcomes of an if-else statement when the condition is true and when it is false.

  1. 1
    Evaluate

    The program evaluates the condition before entering either branch.

  2. 2
    True result

    When the condition is true, the true branch runs and the false branch is skipped.

  3. 3
    False result

    When the condition is false, the true branch is skipped and the false branch runs.

  4. 4
    Continue

    After the selected branch, execution reaches the code that follows the if-else block.

Result

Exactly one branch runs for each condition result.

Code walkthrough
if condition:
    print("accepted")
else:
    print("rejected")
print("finished")
  1. 1
    Start at the if line and evaluate condition.
  2. 2
    For a true result, execute the indented accepted statement and skip the else block.
  3. 3
    For a false result, skip the accepted statement and execute the indented rejected statement.
  4. 4
    In both cases, continue to the finished statement.
  • The condition is evaluated first.
  • Only the branch matching the condition runs.
  • The statement after the if-else block runs after either branch.
Output
If condition is true:
accepted
finished

If condition is false:
rejected
finished
truecondition resultacceptedbranch outputfinishedoutput after the blockfalsecondition resultrejectedbranch outputselectsselectsthenthen
How does a true or false condition change which statement runs and what output the program produces?

Mistakes That Break Branching

  • Common mistake

    Leaving out the colon after if or else.

    What it looks like
    if condition
        statement_for_true
    Why it fails

    The syntax requires a colon after the if line and after the else line.

    Do this instead

    Write if condition: and else:.

  • Common mistake

    Using inconsistent indentation inside a branch.

    What it looks like
    if condition:
        first_statement
      second_statement
    Why it fails

    Statements in a block must be indented consistently.

    Do this instead

    Give all statements belonging to the same branch the same indentation.

  • Common mistake

    Treating if and else as two independent paths that both run.

    What it looks like

    Reading both branch statements as part of one uninterrupted sequence.

    Why it fails

    The branches are mutually exclusive. The condition selects exactly one of them.

    Do this instead

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

  • Common mistake

    Tracing the branch without checking the condition.

    What it looks like

    Assuming the if branch runs before determining whether the condition is true.

    Why it fails

    The condition determines which branch executes.

    Do this instead

    Write down the condition result before following the control flow.

if condition:required colonmissing colonsyntax breaktrue blockconsistent indentationinconsistentindentationblock breakelse:required colonfalse blockconsistent indentationopensfollowed byopensreplacesdisrupts
Where does the intended control flow break when a colon, indentation, or branch choice is incorrect?

Practice the Trace

EASY

Consider this if-else structure:

if condition:
    print("first path")
else:
    print("second path")
print("afterward")

Describe the output when the condition is true, then describe the output when the condition is false. Explain which branch is skipped in each case.

Hints
  • Evaluate the condition before choosing a branch.
  • Exactly one branch runs.
  • The afterward statement is outside the if-else block, so it follows the selected branch.
Best practice

When debugging an if-else statement, trace it in three passes: identify the condition result, mark the branch that executes, and then continue to the code after the block. Also check both colons and the indentation of every statement in each branch.

Key Takeaways

  1. 1
    An if-else statement creates two mutually exclusive branches.
  2. 2
    A true condition selects the if branch; a false condition selects the else branch.
  3. 3
    Exactly one branch always executes because the condition is either true or false.
  4. 4
    Tracing means evaluating the condition first, following only the selected branch, and then continuing afterward.
  5. 5
    The syntax requires colons after if and else, with consistently indented branch blocks.

At a glance

  • If-else statements provide alternative execution through two mutually exclusive branches.
  • The condition determines whether the if branch or the else branch runs.
  • Tracing requires evaluating the condition first and skipping the branch that does not match.
  • Both branch lines require colons, and their blocks must be indented consistently.
  • After one branch finishes, execution continues with the code after the if-else block.

Related concepts

More concepts starting with B