Concepts / If Statements

If Statements

Ordinary program flow executes instructions in their sequence.

  • Programming

When Reading Top to Bottom Is Not Enough

Imagine a program as a list of instructions read from top to bottom. The computer carries out one instruction after the next in the order they appear. This arrangement is straightforward, but it is limited. Once the computer reaches the end of the list, there are no more instructions to execute. Useful programs need two things beyond plain sequence: a way to repeat instructions, and a way to choose what should happen next.

Control structures are the tools that change this ordinary flow. This article focuses on one of them, the if statement, which introduces a decision into program flow. Before reading on, pause and think about a simple case: if a program is told that a score is 45, and the rule is that a score of 50 or more passes, what should the program do? Keep your answer in mind, because the rest of the article shows exactly how a program reaches its result.

Loops and Branches Change Flow Differently

Control structures come in two broad families that are easy to confuse. A loop changes the one-way pattern by allowing a sequence of instructions to be repeated over and over. The important mental model is movement back to the same sequence so that it can run again. Instead of writing each repetition as a separate set of instructions, the program uses a control structure whose purpose is repeated execution.

A branch changes the path through a program rather than repeating the same path. It tests a condition while the program is running and uses the result to decide between two or more different courses of action. This is called conditional execution: a course of action is selected because the condition has one result rather than another. An if statement is the basic form of a branch.

FeatureLoopBranch
Main purposeRepeated execution of a sequenceSelecting between courses of action
Effect on flowReturns control to an earlier point so the sequence runs againSends control down one path rather than another
What drives itRepetition of the same sequenceA condition tested while the program runs
Typical questionShould this sequence run again?Which action should happen now?

Loops and branches both alter ordinary top-to-bottom flow, but in different ways.

How a Condition Becomes a Decision

Programs do not always need to perform every instruction. Sometimes they must choose a path. An if statement creates that choice by examining a boolean-valued expression. The expression is either true or false, and that result determines which action the computer takes. The boolean expression is therefore the heart of the decision: it is the question the program asks, and its answer is what the program uses to move forward.

Key point

The boolean expression determines which path is selected. Everything else in an if statement follows from the true or false answer that expression produces.

Tracing a Simple If Statement

A simple if statement is the one-way form. It either performs one action or skips it. If the boolean expression is true, the contained statement runs. If the expression is false, the contained statement is skipped, and control continues with whatever follows the if statement. The one-way form is useful when the program should perform an action only for a true condition.

python
Output (expected)
Warm day
Check the forecast
Notes on the code
  • temperature > 25 is the boolean expression; here it evaluates to True
  • The indented print('Warm day') is the contained statement, which runs because the condition is true
  • The unindented print('Check the forecast') is not part of the if statement, so it always runs after the decision
temperature > 25boolean expressionprint Warm dayruns when Trueprint Check theforecastalways runs after thedecisionEndTrueFalse: skip contained linecontinue
When the condition temperature > 25 is true, the warning line runs. When it is false, that line is skipped and control moves directly to the next statement.

What do you think happens?

Suppose temperature is changed to 20. Which lines are printed?

  • Warm day and then Check the forecast

  • Only Check the forecast

  • Only Warm day

Reveal answer
Answer:

Only Check the forecast

With temperature set to 20, the expression temperature > 25 is false. The indented print is bypassed, and control continues with the line after the if statement.

If-Else: Choosing Between Two Alternatives

An if-else statement chooses one of two alternatives. The boolean expression sits in the if line. The statement under the if runs when the expression is true, and the statement after else runs when it is false. Exactly one alternative executes. The displayed action is determined at the decision point: the first alternative is bypassed when the condition is false, and the alternative after else is selected instead. The two actions do not both occur.

python
Output (expected)
Try again
Result recorded
Notes on the code
  • score >= 50 is the boolean expression; with score 45 it evaluates to False
  • print('Pass') is the alternative that runs when the expression is true, so it is bypassed here
  • print('Try again') is the alternative after else, so it runs here
  • print('Result recorded') sits outside the if-else and runs after whichever alternative was chosen
score >= 50boolean expressionprint PassTrue alternative: bypassedprint Result recordedstatement after the if-elseprint Try againFalse alternative: runsTrueFalse
The condition score >= 50 leads to exactly one of two alternatives. With score 45, the False path runs and the True path is bypassed. Both paths then lead to the next statement.

Simple If Versus If-Else

An if statement does not always need an else clause. The difference lies in what happens when the expression is false. In a simple if, a false result means the contained action is skipped and execution moves on. In an if-else, a false result means a different action runs, because the else alternative exists for exactly that case.

QuestionSimple ifIf-else
AlternativesOne action, which may be skippedExactly two alternatives, one always runs
When the expression is trueThe contained statement runsThe statement under if runs
When the expression is falseThe contained statement is skippedThe statement after else runs
Typical usePerform an action only when a condition holdsChoose between two different actions

A simple if asks whether to do one thing; an if-else asks which of two things to do.

Mistakes When Tracing a Decision

When an if statement produces an unexpected result, inspect the decision in a fixed order. First identify the boolean expression. Next determine whether its value is true or false. Finally check which statement belongs to that result. The errors below usually come from skipping one of these steps.

  • Common mistake

    Assuming both alternatives of an if-else run

    What it looks like

    With score 45, expecting both Pass and Try again to print.

    Why it fails

    Exactly one alternative executes in an if-else statement. The true and false branches never both occur for the same evaluation.

    Do this instead

    Evaluate the expression first, then follow only the alternative that matches its result.

  • Common mistake

    Treating a simple if as if it always runs its body

    What it looks like
    Believing print('Warm day') appears when temperature is 20.
    Why it fails

    In a simple if, a false expression means the contained statement is skipped and execution continues with the next statement.

    Do this instead

    Check the result of the expression before deciding whether the indented line is reached.

  • Common mistake

    Confusing the lines after the decision with the contained statements

    What it looks like

    Thinking print('Check the forecast') is skipped whenever the condition is false.

    Why it fails

    A statement that is not indented under the if is not part of the if statement, so it runs after the decision regardless of the result.

    Do this instead

    Identify exactly which statements belong to each result before predicting output.

Practice Tracing a Decision

EASY

Using the if-else example with score = 45, predict the output if score is changed to 50. Identify the boolean expression, decide whether it is true or false, and then name which statement runs and which is skipped.

Hints
  • Start by evaluating score >= 50 with the new value.
  • A true expression selects the alternative under if; a false expression selects the alternative after else.
  • The line after the whole if-else runs in either case.

Key Takeaways

  • A program that only executes instructions in sequence has no way to repeat work or choose between paths; control structures change that ordinary flow.
  • A loop repeats a sequence by moving control back to it, while a branch tests a condition at run time and selects one of several courses of action.
  • An if statement evaluates a boolean expression: a simple if either performs its contained action or skips it, while an if-else runs exactly one of two alternatives.
  • To trace a decision, identify the boolean expression, determine whether it is true or false, and then check which statement belongs to that result.