The answersDownload the PDF
Worksheet

F2.7 Loop patterns

Decisions and loops · GCSE · OCR J277 2.2.1, AQA 8525 3.2.2, Edexcel 1CP2 1.2.4 · about 20 min

BugBotLab
NameClassDate

What this lesson is about

Running totals, counting, finding the largest, nested loops and trace tables.

Questions 7 marks in all

  1. [1 mark]What does this program print?

    total = 0
    for d in [40, 35, 30]:
        total = total + d
    print(total, total / 3)
  2. [1 mark]What does this program print?

    count = 0
    for d in [50, 20, 35, 10]:
        if d < 30:
            count = count + 1
    print(count)
  3. [1 mark]What does this program print?

    most = 0
    for d in [12, 51, 30]:
        if d > most:
            most = d
    print(most)
  4. [1 mark]An outer loop runs 3 times and the loop inside it runs 4 times each time. How many times does the inner block run?

  5. [1 mark]A program puts total = 0 inside the loop instead of before it. What goes wrong?

    1. AThe total is reset every time round, so it ends as just the last value
    2. BNothing
    3. CA syntax error
    4. DThe loop never ends
  6. [1 mark]What is a trace table for?

    1. AFollowing the values of variables step by step as an algorithm runs
    2. BDrawing the robot's path
    3. CListing a program's errors
    4. DStoring data in a program
  7. [1 mark]What does this program print?

    for row in range(1, 3):
        for col in range(1, 4):
            print(row, col)

The task: times grid

Print a multiplication grid of five rows and five columns with two nested for loops. Each row is the numbers separated by single spaces, so the first row is 1 2 3 4 5 and the last is 5 10 15 20 25. Work the numbers out; do not type them. The robot must not drive.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for row in range(1, 6):
    print(row)

Plan your program here, then type it in and press Run.

QR code
Do it on the robot
www.bugbotlab.com/learn/f2-7-loop-patterns/
The simulator checks it and tells you when it passes. Nothing to install, no account.

Challenges

  1. Find the smallest distance in eight directions, and which way it is.
  2. Print a triangle of stars with nested loops: one star on the first row, two on the second, up to five.
  3. Take ten distance readings while driving and print how many were under 30, and their average.