Computer ScienceFoundation20 min read

Control Structures in Python

Choosing, repeating, and knowing which loop the problem needs

This topic appears in:

01

Three ways for a program to proceed

Every program ever written is built from three control structures, and the syllabus names all three. Sequence is one statement after another. Selection chooses between alternatives. Iteration repeats.

In Python, which statements belong to a structure is decided by indentation rather than by brackets. That makes the code readable — and makes a misplaced space a genuine bug rather than an untidiness.

Indentation is part of the language

In most languages, indentation is decoration. In Python it is grammar: everything indented under an if runs only when the condition is true, and moving a line out by four spaces changes what the program does. A statement indented one space too far produces an IndentationError; one indented too little runs when it should not, which is worse because it produces no error at all.

02

Selection: if, elif, else

An if tests a condition and runs its block only when the condition is True. elif offers another condition to try if the first failed, and else catches everything remaining.

The order matters. Python tests each condition in turn and stops at the first that is True, so a broad condition placed early prevents any later, narrower one from ever being reached.

if score >= 80:grade = "A"elif score >= 60:grade = "B"else:grade = "F"no need to write score >= 60 and score < 80 — reaching the elif already means the first test failed
Worked example

This grading code always prints "C". Explain why. if m >= 40: print("C") / elif m >= 60: print("B") / elif m >= 80: print("A")

  1. A mark of 90 is tested against the first condition, m >= 40.Python evaluates the conditions strictly in order.
  2. 90 is indeed at least 40, so the condition is True.The test does not know that a later branch would be a better match.
  3. The block runs and the whole chain is abandoned — the elif branches are never examined.That is what elif means: try this only if nothing above matched.
  4. The fix is to order the conditions from the most restrictive downward: 80 first, then 60, then 40.Then a mark of 90 meets the strictest test first and is graded correctly.

The broadest condition is tested first, so it matches everything. Order from most restrictive to least.

03

Iteration: for and while

A for loop repeats a known number of times, or once for each item of a collection. Use it when the count is fixed in advance: every student in a list, every number from 1 to 10.

A while loop repeats as long as a condition remains true, and the number of repetitions is not known when the loop begins. Use it when the stopping point depends on something that happens during the loop — a user typing "quit", a value falling below a threshold.

for i in range(1, 6):# 1, 2, 3, 4, 5 — stops BEFORE 6print(i)while answer != "quit":# unknown number of repeatsanswer = input("> ")range(a, b) runs from a up to but not including b — the off-by-one that costs the most marks

Select Loop total and step through. range(1, 5) gives 1, 2, 3, 4 — the loop body runs four times, not five, because the second number is where it stops rather than the last value used.

The infinite loop

A while loop whose condition never becomes false runs for ever. The usual cause is forgetting to change the variable the condition depends on: while count < 10: with nothing inside that increases count. Before writing a while loop, ask what changes inside it that will eventually stop it — and make sure that change is not inside an if that might never run.

04

Nesting, and choosing the right structure

Control structures can contain each other. A loop containing an if tests each item; a loop containing a loop processes a grid, running the inner loop completely for every single pass of the outer one — so nested loops of 10 and 10 execute the inner body 100 times.

Two keywords occasionally help. break leaves a loop immediately, useful when the answer has been found and further searching is pointless. continue skips the rest of the current pass and moves to the next. Both should be used sparingly: a loop with several exits is harder to reason about than one with a well-chosen condition.

Worked example

Write a program that keeps asking for a number until the user enters one between 1 and 100, then prints it.

  1. The number of attempts is unknown, so this is a while loop, not a for loop.The user may get it right first time or on the twentieth attempt.
  2. Read a value once before the loop: n = int(input("Enter 1-100: ")).The condition needs something to test on its first evaluation.
  3. while n < 1 or n > 100: — repeat while the value is invalid.The condition describes when to keep looping, which is the opposite of the acceptance rule.
  4. Inside: print a message and read again, so n changes each pass.Without a new input the condition never changes and the loop never ends.
  5. After the loop, print(n).Reaching this line means the condition failed, so the value must be valid.

A while loop testing for the invalid range, reading a new value each pass.

Before you leave this chapter

  1. Sequence, selection, iteration — every program is built from these three.
  2. Indentation decides what belongs to a block, and is part of the language.
  3. Order if/elif conditions from most restrictive to least, or the broad one matches everything.
  4. for = known number of repeats; while = unknown, condition-controlled.
  5. range(a, b) stops before b, and a while loop must change the variable its condition tests.

Practice questions

6 questions · 20 marks · full working on every one

Try each one on paper first, then open the working. The marks are shown where they are actually awarded, because that is where they are actually lost.

Short questions

3 · 6 marks

Two marks each, in the style of the short-question section of the paper. Answer in two or three lines.

SQ1[2 marks]
Name the three control structures and give one Python keyword for each.
Model answer

Sequence — statements written one after another, needing no keyword. Selectionif. Iterationfor or while.

Examiner tip. Sequence is the one students forget, because it needs no keyword. It is still one of the three.

SQ2[2 marks]
When should a while loop be used instead of a for loop?
Model answer

When the number of repetitions is not known in advance and depends on a condition evaluated during the loop — for example repeating until the user enters valid input or types "quit". A for loop is used when the count is fixed beforehand.

Examiner tip. The phrase "not known in advance" is what the mark scheme is looking for. Both halves of the comparison should appear.

SQ3[2 marks]
How many times does the body of for i in range(2, 7): execute?
Model answer

Five times, with i taking the values 2, 3, 4, 5 and 6. The upper bound 7 is where the sequence stops and is not itself used.

Examiner tip. Count the values rather than subtracting in your head. Writing them out takes three seconds and removes the off-by-one entirely.

Solved numericals

2 · 8 marks

Full working, one step per line, with the marks shown where they are awarded.

N1[4 marks]
Write a Python program that prints the numbers from 1 to 20 that are divisible by 3.
Full working
  1. for n in range(1, 21): — the upper bound must be 21 to include 20the off-by-one is examined here[1]
  2. if n % 3 == 0:the remainder test for divisibility[1]
  3. print(n) correctly indented inside the ifindentation is part of the mark[1]
  4. Output: 3, 6, 9, 12, 15, 18[1]

A for loop over range(1, 21) with an if n % 3 == 0 test inside.

Examiner tip. To include 20, the range must end at 21. This is the single most common slip in Python questions and it costs a mark every time.

N2[4 marks]
This code is intended to count down from 5 to 1 but instead runs for ever. Identify the fault and correct it. count = 5 / while count > 0: / print(count)
Full working
  1. Nothing inside the loop changes count[1]
  2. So the condition count > 0 is true on every pass and never becomes false — an infinite loopnaming it as infinite is expected[1]
  3. Add count = count - 1 inside the loopaccept count -= 1[1]
  4. It must be indented inside the loop; placed outside it would run only once, after the loopthe indentation point is a mark[1]

The loop variable is never decremented. Add count = count - 1 indented inside the loop.

Examiner tip. For every while loop, ask what changes inside it that will eventually stop it. If nothing does, it is infinite.

Long questions

1 · 6 marks

Theory and numerical together, as they appear in the long-question section.

LQ1[6 marks]
A program should read ten test marks, count how many are 50 or above, and print both the count and the average.
  1. State which loop type is appropriate and why.
  2. Write the program.
  3. Explain where the print statements must be placed and why.
Mark scheme
  1. A for loop, because the number of marks is known in advance to be tenthe reason must be given[1]
  2. Initialise total = 0 and passes = 0 before the loopaccumulators must start outside the loop[1]
  3. for i in range(10): then read a mark and add it to total[1]
  4. if mark >= 50: passes = passes + 1, correctly indented inside the loop[1]
  5. After the loop: print(passes) and print(total / 10)[1]
  6. The prints must be outside the loop, because inside they would run on every pass and print ten partial results instead of one final answerthe reason is the mark[1]

(a) for, since ten is known (b) accumulators before, loop reads and tests, prints after (c) outside, or they print ten partial results

Examiner tip. Initialising the accumulators inside the loop is the other version of this error: total = 0 in the wrong place resets it every pass and the answer is always the last mark.