Class 8 Computer Science — Blocks and indentation
Read a program's indentation to say which lines belong to which block, and how often each line runs.
Name: ________________________
1.Sort each line of this program by how many times it runs.
total = 0 for n in range(1, 4): total = total + n print(n) print(total) print(total * 2)Groups: Runs once · Runs three times
- total = 0
- print(n)
- print(total * 2)
- total = total + n
- print(total)
2.This program prints four numbers. Put them in the order they appear on the screen.
total = 0 for n in range(1, 4): total = total + 5 print(total) print(total - 12)- 10
- 15
- 3
- 5
3.This one has an else branch as well. What is total at the end?
total = 0 for n in range(1, 5): if n > 2: total = total + 1 else: total = total + 1004.This program was meant to show the total once, at the very end, but it shows a number four times over. What went wrong?
total = 0 for n in range(1, 5): total = total + n print(total)- a) The printing line is indented, so it sits inside the loop and runs every trip round
- b) The loop has been written to go round one time too many
- c) The total is set to 0 on the wrong line of the program
- d) A program is only allowed to print one number in total
5.Both of the printing lines are indented here. How many numbers does it print?
for n in range(1, 4): print(n) print(99)6.The last line has been brought back out to the left. What is total at the end?
total = 0 for n in range(1, 4): total = total + 10 total = total + 17.Follow this code by hand. What is the second number it prints?
total = 0 for n in range(2, 6): total = total + n print(total) print(total * 2)8.One of these four lines runs a different number of times from the other three. Which one?
for n in range(1, 4): print(n) print(n * 2) print(n * 3) print(0)- a) The line printing n times 2
- b) The line printing n
- c) The line printing n times 3
- d) The line printing 0
Answer key — Class 8 Computer Science — Blocks and indentation
- 1. total = 0 → Runs once; total = total + n → Runs three times; print(n) → Runs three times; print(total) → Runs once; print(total * 2) → Runs once
- 2. 1. 5 2. 10 3. 15 4. 3
- 3. 202
- 4. a) The printing line is indented, so it sits inside the loop and runs every trip round
- 5. 6
- 6. 31
- 7. 28
- 8. d) The line printing 0