View as PDF

COMPUTING AND DIGITAL LITERACY

Loops

Difficulty level: Intermediate

Computing and Digital Literacy

This document was made by AI and there may be mistakes. If a question or answer looks wrong, use the Flag a mistake button to let Brett know so he can fix it.

Overview of the concept

This is how a program repeats a job without rewriting it, like a music app playing the next song until the playlist ends. A loop tells a program to do the same job again and again until it is done, which is how a computer handles a thousand items as easily as one. Your music app uses a loop to play every song, a game uses one to keep the action going, and a shop website uses one to show every product on a page.

Worked examples

Example 1

What is the output of the loop for i in range(1, 4): print(i)?

Solution

for i in range(1, 4):

print(i)

Output: 1, 2, 3

range(1, 4) gives the values 1, 2, and 3; the end value 4 is not included.

The loop takes each value in turn, stores it in i, and runs the block.

It prints 1, then 2, then 3, and stops when the values run out.

Example 2

Add numbers with a loop

Solution

total = 0

for n in [1, 2, 3, 4]:

total = total + n

Final total: 10

Start total at 0 before the loop.

Each pass adds the next number: 0+1=1, 1+2=3, 3+3=6, 6+4=10

After the last value, the loop ends and total holds 10.

Practice questions

1

What does range(1, 4) give?

2

What is the output of 'for i in range(3, 7): print(i)'?

3

What is the output of 'for i in range(1, 10, 3): print(i)'?

4

How many times does 'for i in range(1, 4): print(i)' print?

times
5

Add 1 + 2 + 3 with a loop trace. What is the total?

6

Trace this loop: total = 1; for n in [2, 3, 4]: total = total * n. What is the final total?

7

What is the output of this loop? i = 1; while i < 4: print(i); i = i + 1

8

Trace this loop: total = 0; for n in [1, 2, 3, 4, 5]: total = total + 2. What is the final total?

9

What is a while loop?

10

What must every while loop eventually do to avoid running forever?

ANSWER KEY

1. 1, 2, 3

2. 3, 4, 5, 6

3. 1, 4, 7

4. 3 times

5. 6

6. 24

7. 1, 2, 3

8. 10

9. A loop that repeats while a condition stays True

10. Reach a state where its condition becomes False