Grade 7 Computer Science · Decisions

A branch — exactly one path

The condition reduces to a truth value, and that value chooses which part runs.

Two paths written, only one runs

Both the message Adult and the message Minor are written in the program, and on every run only one of them appears. Even so, beginners keep being surprised to find a line that ran “despite the condition”. What are they missing?

So far every line always ran. Now the program is given a choice: there is a passage that runs only if something is true, and another that runs only if it is not. That is all it takes for a program to stop being a fixed list and start responding.

Both paths are written; only one of them runs on any given run.
age = 15
if age >= 18:
    print("Adult")
else:
    print("Minor")
print("Done")
The stageWhat happens in it
Reducing the conditionThe expression becomes true or false
Choosing a pathExactly one of the two runs
A shared continuationWhat comes after both always runs

Why “exactly one” and not “perhaps both”

A truth value can be only one of two, so there is no state in which both paths are chosen and none in which neither is. That is a very strong property for checking: if you wrote a branch and you see both messages in the output, the problem is not in the condition — it is a sign that one of the printings is not inside the branch at all. The output tells you something about the structure, not about the condition, and that shortens the search a great deal.

Example 1 — following a branch

  1. The value of the age is fifteen.
  2. The condition “at least eighteen” reduces to false.
  3. So only the second passage runs.
  4. And after it the line outside both runs.

Example 2 — reading output to locate structure

  1. Both of the branch’s messages appear in the output.
  2. But exactly one of them should run.
  3. So one of them is not inside the branch.
  4. One looks in the structure and not in the condition.
Try it in your head: with age 20, Adult and Done would be printed.