For Loops

Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.

For Loops

Name:
Date:
Class:

Quick Questions

Shade in the A or B circle for each question.

1. What does a for loop do?
A Loops forever
B Loops through each item in a sequence
2. for x in [10,20,30]:\n print(x)\nWhat prints?
A 10, 20, 30
B 30
3. for char in 'Hi':\n print(char)\nWhat prints?
A Hi
B H then i
4. What keyword follows 'for x'?
A in
B of
5. How many times does 'for i in range(3):' loop?
A 3 times
B 4 times

Match the Pairs

Draw a line connecting each item on the left to its match on the right.

Left columnRight column
1for x in range(5) print(x) AOutput: 6
2for in range(5): print('hi') BOk: Loop through list
3for char in 'hello': print(char) CError: Missing colon after for
4for item in [1, 2, 3]: print(item) DValid: Loop through string
5for i in range(3): print(i) EError: Missing loop variable
6total = 0 for n in [1,2,3]: total += n print(total) FOutput: 0 1 2

Definitions

for

Fill in the Blanks

Complete each line of code by filling in the missing parts.

1.
___ i in [1, 2, 3]: print(i)
2.
for i __ [1, 2, 3]: print(i)
3.
for char in 'hello'_ print(char)
4.
for color __ ['red', 'blue']: print(color)
5.
for i in _____(5): print(i)

Spot the Error

Shade in the letter of the line that contains an error.

Question 1
A total = 0
B for i in [1, 2, 3]
C total += i
D print(i)
E print('Sum:', total)
Question 2
A total = 0
B for i in [1, 2, 3]:
C print(i)
D total += i
E print('Done')
Question 3
A total = 0
B For i in [1, 2, 3]:
C total += i
D print(i)
E print('Sum:', total)
Question 4
A total = 0
B for i of [1, 2, 3]:
C total += i
D print(i)
E print('Sum:', total)
Question 5
A total = 0
B for i in 5:
C total += i
D print('Sum:', total)

Answer Key

For Loops
Section A: Quick Questions
Q1
B — Loops through each item in a sequence
Q2
A — 10, 20, 30
Q3
B — H then i
Q4
A — in
Q5
A — 3 times
Section B: Match the Pairs
Q1
for x in range(5) print(x) → Error: Missing colon after for
Q2
for in range(5): print('hi') → Error: Missing loop variable
Q3
for char in 'hello': print(char) → Valid: Loop through string
Q4
for item in [1, 2, 3]: print(item) → Ok: Loop through list
Q5
for i in range(3): print(i) → Output: 0 1 2
Q6
total = 0 for n in [1,2,3]: total += n print(total) → Output: 6
Section C: Definitions
Q1
for — Loop that iterates through each item in a sequence.~~in
Section D: Fill in the Blanks
Q1
for i in [1, 2, 3]: print(i)
Q2
for i in [1, 2, 3]: print(i)
Q3
for char in 'hello': print(char)
Q4
for color in ['red', 'blue']: print(color)
Q5
for i in range(5): print(i)
Section E: Spot the Error
Q1
B — Missing colon at the end of the for line
Q2
C — The print line must be indented inside the for loop
Q3
B — for must be lowercase: For is not valid Python
Q4
B — Use 'in', not 'of': Python syntax is: for x in sequence:
Q5
B — Can't loop over a plain number: use range(5) to loop 5 times