Grade 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.Follow this code by hand. What is count at the end?
count = 0 for n in range(1, 7): if n > 2: count = count + 1 count = count + 102.Follow this code by hand. How many times does the most deeply indented line run?
for n in range(1, 5): print(n) if n > 100: print(n * 2)3.Both of the printing lines are indented here. How many numbers does it print?
for n in range(1, 4): print(n) print(99)4.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) A program is only allowed to print one number in total
- b) The loop has been written to go round one time too many
- c) The printing line is indented, so it sits inside the loop and runs every trip round
- d) The total is set to 0 on the wrong line of the program
5.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 + 1006.A test sits inside the loop here. What is total at the end?
total = 0 for n in range(1, 6): if n > 3: total = total + n7.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 + 18.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
- print(total * 2)
- print(n)
- print(total)
- total = 0
- total = total + n
Answer key — Grade 8 Computer Science — Blocks and indentation
- 1. 64
- 2.
- 0
- none
- 3. 6
- 4. c) The printing line is indented, so it sits inside the loop and runs every trip round
- 5. 202
- 6. 9
- 7. 31
- 8. total = 0 → Runs once; total = total + n → Runs three times; print(n) → Runs three times; print(total) → Runs once; print(total * 2) → Runs once