Sequence, selection and iteration

GCSE Computer Science (Edexcel) · Edexcel 1CP2 · 6.2 · Problem solving with programming

40 exam-style questions plus unlimited generated ones on this topic, at up to four difficulty levels, with full mark schemes. Notes and past-paper booklets are open to everyone. Practice needs a free account.

Or take a quick quiz: 10 questions on this subtopic in GCSE Computer Science (Edexcel), marked as you tap.

Revision notes

Sequence, selection and repetition are the building blocks of every program. You need to read, trace, complete and write Python code that uses if, elif and else, count-controlled for loops, condition-controlled while loops, and loops that visit every item in a list or string. They appear throughout Paper 2.

Key facts

  • Sequence: statements run in the order written
  • Selection: if / elif / else (only the first True branch runs)
  • Count-controlled loop: for i in range(n): repeats n times
  • Condition-controlled loop: while condition: repeats while the condition is True
  • range(n) gives 0 to n − 1
  • range(a, b) gives a to b − 1; range(a, b, s) goes up in steps of s
  • Iteration over a structure: for item in myList: / for char in myString:
  • if, elif, else, for and while lines end with a colon; the block under them is indented
  • Running total: total = 0 before the loop, add inside it, output after it

Notes

Sequence

  • Sequence: statements run one after another, in the order they are written. Swapping two lines can change the result.
  • Initialisation gives a variable its first value before it is used (total = 0); assignment changes its value (total = total + price).
  • Programs are built from variables and constants, assignments, input and output, selection, repetition, iteration, data structures and subprograms.

Selection

diagram
  • if runs its block only when its condition is True; the else block runs when it is False.
  • Input markmark >= 40?YesNoOutput "Pass"Output "Fail"Stop
    if … else as a flowchart: the condition picks one branch, then both paths join again.
  • elif adds more conditions. They are checked from the top and only the first True branch runs, so when you use >=, test the highest value first.
  • Every if, elif and else line ends with a colon, and the block under it is indented.
  • Nested selection puts one if inside another, so the inner condition is only tested when the outer condition is True. Grade 7+ only

Repetition

diagram
  • Count-controlled loop: repeats a fixed number of times. for i in range(4): runs 4 times, with i taking the values 0, 1, 2, 3.
  • range(start, stop, step) stops before the stop value: range(2, 11, 3) gives 2, 5, 8 and range(5, 0, -1) gives 5, 4, 3, 2, 1.
  • Condition-controlled loop: while condition: repeats while the condition is True. The condition is checked before each pass, so the body may never run.
  • count = 1count <= 3?YesOutput countcount = count + 1loop backNoStopOutput: 1, 2, 3The condition ischecked beforeevery pass.
    A while loop as a flowchart: while count <= 3: repeats the two steps inside the loop until the condition is False.
  • Something inside a while loop must eventually make the condition False, or the loop never ends (an infinite loop).
  • Use while for validation, menus and 'keep going until the user enters 0'.

Iteration over a data structure

  • for item in prices: visits every item in a list, in order; for letter in word: visits every character in a string.
  • Use for i in range(len(names)): when you need the index as well, e.g. to match names[i] with scores[i].
  • Nested loops: the inner loop runs all the way through for every pass of the outer loop, so 3 outer passes × 4 inner passes = 12 runs of the inner block. Grade 7+ only
  • Give each loop a single entry and exit point: end a while loop through its condition, e.g. with a Boolean flag such as found, rather than jumping out of it. Grade 8+ only

How to answer each type of question

State the type of loop and explain why

2 marksGrade 5
  1. Decide whether the number of repeats is known before the loop starts.
  2. Known: count-controlled (for). Not known, repeats until something happens: condition-controlled (while).
  3. Give the reason using the context of the question.

Example. A program keeps asking the user for a password until the correct password is entered.
State the type of loop that should be used. Give a reason for your answer. (2)

Show the model answerHide the model answer
A condition-controlled (while) loop (1), because the number of attempts the user needs is not known in advance: the loop must repeat until the correct password is entered (1).

State the output of a program with a loop

2 to 4 marksGrade 5
  1. Write down the values the loop variable takes, e.g. from range().
  2. Draw a trace table with a column for each variable and one for the output.
  3. Follow the code line by line for every pass and write each output exactly, on its own line.

Example.

01 total = 0
02 for n in range(3, 12, 4):
03     total = total + n
04     print(n, total)
(a) State the output of the program. (2)
(b) State how many times line 03 is run. (1)

Show the model answerHide the model answer
(a) 3 3, then 7 10, then 11 21, each on its own line: correct values of n (3, 7, 11) (1); correct totals (3, 10, 21)
(1)
(b) 3
(1)

Write selection code

3 to 4 marksGrade 5
  1. List the cases and their limits from the question.
  2. Use if for the first case, elif for each middle case and else for the last one.
  3. Check the boundaries: test values on each side of every limit (e.g. 11 and 12).

Example. A cinema charges £5 for children under 12, £9 for people aged 12 to 64 and £6 for people aged 65 or over. The age is stored in the integer variable age.
Write Python code that sets the variable price to the correct ticket price. (4)

Show the model answerHide the model answer
if age < 12:
    price = 5
elif age < 65:
    price = 9
else:
    price = 6
Correct condition for under 12 (1); elif with a correct condition for 12 to 64 (1); else (or age >= 65) for 65 or over (1); correct prices with correct colons and indentation (1).

Write a program that uses a while loop

4 to 6 marksGrade 6
  1. Initialise counters and totals before the loop.
  2. Input the first value before the loop, so the condition can be tested.
  3. Inside the loop, process the value, then input the next one.
  4. Output the results after the loop, not inside it.

Example. Write a program that asks the user to enter whole numbers until they enter 0. It must then output how many numbers were entered (not counting the 0) and their total. (6)

Show the model answerHide the model answer
count = 0
total = 0
number = int(input("Enter a number (0 to stop): "))
while number != 0:
    count = count + 1
    total = total + number
    number = int(input("Enter a number (0 to stop): "))
print("Count:", count)
print("Total:", total)
Sets count and total to 0 (1); inputs the first number as an integer before the loop (1); a while loop that stops when 0 is entered (1); adds 1 to count and the number to total inside the loop (1); inputs the next number inside the loop (1); outputs the count and total after the loop (1).

Trace nested loops

2 to 3 marksGrade 7
  1. Take one pass of the outer loop at a time.
  2. For that pass, run the inner loop all the way through before going back to the outer loop.
  3. To count runs of the inner block, add up the inner passes for each outer pass.

Example.

01 for row in range(1, 4):
02     line = ""
03     for col in range(row):
04         line = line + "#"
05     print(line)
(a) State the output of the program. (2)
(b) State how many times line 04 is run. (1)

Show the model answerHide the model answer
(a) #, then ##, then ###, each on its own line: three lines of output (1); with 1, 2 and 3 # characters
(1)
(b) 6, because 1 + 2 + 3 = 6
(1)

Don’t lose marks

  • Forgetting the colon at the end of an if, elif, else, for or while line: a syntax error.
  • Using range(1, 10) to count from 1 to 10. It stops at 9; use range(1, 11).
  • Forgetting to input again, or to change the variable, inside a while loop, so the loop never ends.
  • Indenting a print() so it runs on every pass when the output is only needed once, after the loop.
  • Using separate if statements where elif is needed, so more than one branch runs.
  • Setting a total to 0 inside the loop, so it only ever holds the last value.

More tips

Memory tricks

  • range() never reaches its stop value: think 'up to but not including'.
  • range(a, b) produces b − a values, so range(1, 11) gives 10 values: 1 to 10.
  • Know how many repeats? Use for. Don't know? Use while.
  • With elif, the first True condition wins, so with >= start from the top value and work down.
  • If the inner loop always has the same number of passes, runs of the inner block = outer passes × inner passes.

Exam technique

  • Trace with a table: one column per variable and one for output, updated line by line.
  • Read whether output is needed for each item (inside the loop) or once at the end (after the loop).
  • Test your selection code with a value on each side of every boundary, e.g. 11 and 12, 64 and 65.
  • In the onscreen exam, keep the variable names and structure you are given and add to them, rather than rewriting.

What each grade needs

What you need to be able to do, from the first marks up to the top grade.

  1. Grade 3
    Recognise sequence, selection and iteration in codePoint out the lines that run in order, the lines that make a decision and the lines that repeat.
  2. Grade 4
    Write if, elif and else statementsChoose between two or more paths using conditions, colons and correct indentation.
  3. Grade 4
    Use range() to control a for loopKnow that range(5) gives 0 to 4 and range(1, 6) gives 1 to 5.
  4. Grade 5
    Choose count- or condition-controlled loopsUse for when the number of repeats is known and while when it depends on a condition.
  5. Grade 5
    Trace loops to find the outputUse a trace table to follow each variable through every pass of a loop.
  6. Grade 6
    Iterate over every item of a data structureUse for item in a list, or for character in a string, to process each one in turn.
  7. Grade 7
    Use nested loops and nested selectionPut a loop or if inside another and work out how many times the inner block runs.
  8. Grade 8
    Combine constructs to solve unfamiliar problemsDecompose the task, choose the right constructs and give each loop a single exit point.

Quick recall

Cover the answers and test yourself. The app has these as flashcards that come back just before you'd forget them.

Look at this program.
01 total = 0
02 count = 0
03 number = int(input("Enter a number (0 to stop): "))
04 while number != 0:
05     total = total + number
06     count = count + 1
07     number = int(input("Enter a number (0 to stop): "))
08 if count > 0:
09     print("Mean:", total / count)
10 else:
11     print("No numbers entered")
Give the line number where repetition starts.
04
State the Python keyword that starts a condition-controlled loop.
while
A program should print the square of each number from 1 to 5, and whether each square is even or odd. The program below contains two errors.
01 # Square number table
02 print("Square numbers")
03 for i in range(1, 5):
04     square = i * i
05     print(i, "squared is", square)
06     if square % 2 = 0:
07         print("Even")
08     else:
09         print("Odd")
10 print("Finished")
Identify the type of error on line 06.
Syntax error (= is used instead of ==).
Name the construct shown by this code.
age = 15
fee = age * 2
print(fee)
Sequence
State what is meant by iteration in a program.
Repeating one or more instructions, for example using a loop.

Sample questions

Written for this site in the style of Edexcel exam questions. They are not taken from real past papers.

Question 1Easy5 marks
Look at this program.
01 total = 0
02 count = 0
03 number = int(input("Enter a number (0 to stop): "))
04 while number != 0:
05     total = total + number
06     count = count + 1
07     number = int(input("Enter a number (0 to stop): "))
08 if count > 0:
09     print("Mean:", total / count)
10 else:
11     print("No numbers entered")
(a) Give the line number where repetition starts.
[1]
(b) Give the line number where selection starts.
[1]
(c) State whether the loop is count-controlled or condition-controlled.
[1]
(d) The user enters 6, 10, 5 and 0. State the output.
[1]
(e) Define the term sequence in a program.
[1]
Show the answer and mark scheme
(a) Answer: 04
  • 04
(b) Answer: 08
  • 08
(c) Answer: Condition-controlled
  • condition-controlled
(d) Answer: Mean: 7.0
  • Mean: 7.0 (accept 7)
(e) Answer: The instructions are carried out one after another, in the order in which they are written.
  • instructions are carried out one after another / in the order they are written
Question 2Medium8 marks
Here are two programs.
Program A
for n in range(3, 20, 4):
    print(n * 2)
Program B
total = 0
number = 1
while total < 50:
    total = total + number
    number = number * 2
print(number)
(a) State the numbers output by Program A.
[2]
(b) Write a program that uses a while loop to produce exactly the same output as Program A.
[3]
(c) State the output of Program B.
[1]
(d) Explain why a while loop is used in Program B rather than a for loop.
[2]
Show the answer and mark scheme
(a) Answer: 6, 14, 22, 30, 38
  • 6, 14 and 22
  • 30 and 38, with no other numbers
(b) Answer:
n = 3
while n < 20:
    print(n * 2)
    n = n + 4
  • n set to 3 before the loop
  • while n < 20: (accept n <= 19)
  • n increased by 4 inside the loop, after the print statement
(c) Answer: 64
  • 64
(d) Answer: The number of passes is not known in advance, because it depends on when the total reaches 50. A while loop repeats until a condition is met.
  • the number of passes / repetitions is not known in advance (it depends on when total reaches 50)
  • a while loop is condition-controlled / repeats while a condition is True
Question 3Hard8 marks
A primary school wants a program to help pupils practise their times tables.
Write a program that:
  • asks the user 10 multiplication questions
  • makes each question by choosing two random whole numbers from 2 to 12
  • inputs the user's answer to each question and outputs whether it is correct; if it is wrong, the correct answer is also output
  • outputs the number of correct answers at the end, followed by Well done if the user got 8 or more correct.
[8]
Show the answer and mark scheme
Answer:
import random

score = 0
for question in range(10):
    a = random.randint(2, 12)
    b = random.randint(2, 12)
    answer = int(input("What is " + str(a) + " x " + str(b) + "? "))
    if answer == a * b:
        print("Correct")
        score = score + 1
    else:
        print("Wrong, the answer is", a * b)
print("You scored", score, "out of 10")
if score >= 8:
    print("Well done")
  • imports the random library and uses random.randint(2, 12)
  • a loop that repeats exactly 10 times
  • two new random numbers are chosen inside the loop, for every question
  • displays each question, including both numbers
  • inputs the answer and converts it to an integer
  • compares the answer with the product of the two numbers
  • outputs a message for a correct answer, and outputs the correct answer when the answer is wrong
  • a score is set to 0 before the loop and increased by 1 for each correct answer
  • after the loop, outputs the score, and outputs Well done only when the score is 8 or more

More in Problem solving with programming

Stuck? Get 1-to-1 help.

Chhetri Academy tutors GCSE and A level Maths and Science online, with a free 30-minute trial lesson.