Concepts / Write Simple if Statements

Write Simple if Statements

An if-else statement selects exactly one of those blocks.

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

Two Possible Paths

Many programs need to respond differently depending on a condition. Alternative execution handles this situation by providing two possible blocks of code: one block for when a condition is true and another block for when it is false. An if-else statement selects exactly one of those blocks.

conditionTrue or Falseif blockcondition is Truenext statementelse blockcondition is FalseTrueFalseafter branchafter branch
What happens next when a condition is true versus when it is false, and which of the two code blocks executes?

A First Execution Trace

Code walkthrough
number = 7

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

print(result)
  1. 1
    Python evaluates number % 2 == 0 first.
  2. 2
    The condition is False for the value 7.
  3. 3
    Because the condition is false, Python does not execute the indented if block.
  4. 4
    Python executes the indented else block instead.
  5. 5
    Execution continues to the print statement after the if-else statement.
  • The variable number has the value 7.
  • The condition checks whether the remainder from dividing number by 2 equals 0.
  • The condition is False for 7, so the if block is skipped.
  • The else block assigns the value odd to result.
  • The print statement displays odd.
Output
odd
number = 7input valuenumber % 2 == 0Falseif blockskippedprint(result)oddresult = oddelse blockevaluateFalseFalse branchthen
Given the input 7 and the condition number % 2 == 0, which branch does program control follow and where does execution rejoin afterward?

How Python Chooses

When Python encounters an if-else statement, it evaluates the condition first. A condition is a boolean expression, so its result is either True or False. If the result is True, Python executes the indented code under if and skips the else block. If the result is False, Python skips the if block and executes the indented code under else. Exactly one block runs: never both and never neither.

boolean conditionTrue or Falseindented if coderuns when Trueindented else coderuns when Falsefollowing statementif codeskipped when Falseelse codeskipped when TrueTrueTrueFalseFalseafter blockafter block
How does the condition's truth value determine whether an indented block runs or is skipped?
ifkeywordprint("pass")indented code blockscore >= 60condition:starts blockfollowed byfollowed byblock contains
How do the condition, colon, indentation, and code block fit together in a correctly written if statement?

Writing the Structure

python

The condition follows if, and a colon must follow the condition. The statements controlled by if must be indented. The else line also requires a colon, and the statements controlled by else must be indented. The two indented regions are the two alternative blocks.

Checking an Unexpected Result

Before
temperature = 20

if temperature < 10:
    message = "cold"
else:
    message = "not cold"

print(message)

Expected the cold branch to run.

After
temperature = 20

if temperature < 10:
    message = "cold"
else:
    message = "not cold"

print(message)

The condition 20 < 10 is False, so the else branch runs and the output is not cold.

Debugging an if statement begins at the condition. Compare the actual input with the condition and decide whether the result is True or False. Then check whether the program follows the corresponding branch. If the branch is correct but the result still seems wrong, inspect the statements inside that indented block.

  • Common mistake

    Leaving out the colon after the condition.

    What it looks like
    if score >= 60
    Why it fails

    The if statement requires a colon after its condition.

    Do this instead
    Write if score >= 60:
  • 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

    Write else:

  • Common mistake

    Failing to indent the code controlled by the condition.

    What it looks like
    if score >= 60:
    print("pass")
    Why it fails

    The code that belongs to the if block must be indented.

    Do this instead

    Indent the statement under if.

  • Common mistake

    Assuming both branches execute.

    What it looks like

    A condition is True, but expecting both the if and else messages.

    Why it fails

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

    Do this instead

    Evaluate the condition and follow only the matching branch.

temperature < 10expected Truecoldtemperature < 10actual Falsenot coldexpected pathactual path
At which condition or branch does actual execution diverge from the expected path, and what input caused the divergence?

Branch Prediction Practice

What do you think happens?

Which message is printed when points has the value 42?

  • high

  • low

Reveal answer
Answer:

high

The condition points >= 40 is True for 42. Python executes the if block and skips the else block.

python
EASY

Trace the code before running it. Write down the condition, decide whether it is True or False, identify the branch that executes, and state what the program prints.

Hints
  • Start with the value of points.
  • Evaluate points >= 40.
  • Only one indented block executes.

Key Takeaways

  • An if-else statement provides two alternative execution paths.
  • Python evaluates the condition first and uses its True or False result to select a branch.
  • Exactly one block executes in an if-else statement; the other block is skipped.
  • A correct statement needs a colon after the if condition and after else, plus proper indentation for each block.
  • To debug unexpected behavior, evaluate the condition with the actual input and trace the selected branch.

More concepts starting with W