Decisions and loops · GCSE · OCR J277 2.2.1, AQA 8525 3.2.2, Edexcel 1CP2 1.2.4 · about 20 min
Running totals, counting, finding the largest, nested loops and trace tables.
[1 mark]What does this program print?
total = 0
for d in [40, 35, 30]:
total = total + d
print(total, total / 3)105 35.0
A running total adds each value: 105. Dividing by how many gives the average, 35.0.
[1 mark]What does this program print?
count = 0
for d in [50, 20, 35, 10]:
if d < 30:
count = count + 1
print(count)2
Only 20 and 10 are under 30, so the count is 2.
[1 mark]What does this program print?
most = 0
for d in [12, 51, 30]:
if d > most:
most = d
print(most)51
most is replaced whenever a bigger value turns up, so it ends as the largest, 51.
[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?
[1 mark]A program puts total = 0 inside the loop instead of before it. What goes wrong?
[1 mark]What is a trace table for?
[1 mark]What does this program print?
for row in range(1, 3):
for col in range(1, 4):
print(row, col)1 1 1 2 1 3 2 1 2 2 2 3
For each row, the inner loop goes through all three columns before the row changes.
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)The hint students can ask for: One loop for the rows, and another inside it for the columns. Print without starting a new line inside the inner loop, then start one when each row finishes.
from bugbot import *
connect()
for row in range(1, 6):
for col in range(1, 6):
print(row * col, end=' ')
print()
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.