Python loops
Answers are for parents and teachers.
1
Write two Python programs. One prints Hello 6 times. The other prints the numbers 1 to 6.
Model answer (lines are separated by /, and [indent] means four spaces at the start of the line): (first program) for k in range(6): / [indent] print("Hello"). (second program) for n in range(1, 7): / [indent] print(n)
2
Write this pseudocode as a Python for loop. Then say what is printed.
Pseudocode
1FOR m ← 3 TO 7 2 OUTPUT m * 10 3NEXT m
Model answer (lines are separated by /, and [indent] means four spaces at the start of the line): for m in range(3, 8): / [indent] print(m * 10). Check: It prints 30, 40, 50, 60 and 70, each on its own line.
3
What does this program print at the end?
Python
1total = 0 2for n in range(1, 5): 3 total = total + n * n 4print(total)
total goes 1, 5, 14 and 30 (adding 1, 4, 9 and 16). The only print is after the loop, so the output is 30.
4
This program should print 1 to 5, but it has three mistakes. Find all three and write the correct program.
Python
1For c in range(1, 5) 2 print(c)
Mistakes: the keyword is written For (it must be for), the colon is missing, and the stop value 5 should be 6. Correct: for c in range(1, 6): with print(c) indented below it.
5
Explain in your own words why for k in range(2, 6) runs 4 times and not 5 times. How can you work out the number of runs without listing the values?
range stops before the stop value, so 6 is never used. The values are 2, 3, 4 and 5. The number of runs is stop − start, which is 6 − 2 = 4.