This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: for loops

for loops in action

face Josiah Wang Joe Stacey

Here are some questions for you to see for loops in action!

It might sometimes be helpful to think of the code at a higher level of semantic abstraction (what does it do?), rather than trying to ‘trace’ the details of the output step by step. See some of my explanations for examples of how I summarised each piece of code in simple English.

1 2 3 4 5

Question 1

What is the output of the following code snippet? Type Error if it results in an error. Type Infinite if it ends up in an infinite loop.

numbers = [5, 1, 3]
total = 0
for number in numbers:
    total = total + number
print(total)

9
Explanation:

This piece of code sums the numbers in a list.

Question 2

What is the output of the following code snippet? Type Error if it results in an error. Type Infinite if it ends up in an infinite loop.

numbers = [1, 2, 3, 4, 5, 6] 
total = 0
for number in numbers:
    if number % 2 == 0:
        total = total + number
print(total)

12
Explanation:

This piece of code adds up all even numbers in a list. Note that there is no need to increment any counters or worry about infinite loops in this example - you are just reading values from a fixed (and finite) list.

Question 3

What is the output of the following code snippet? Type Error if it results in an error. Type Infinite if it ends up in an infinite loop.

numbers = [3, 2, 6, 0, 7, 12] 
total = 0
for number in numbers:
    if number <= 0:
        break
    total = total + number
print(total)

11
Explanation:

This piece of code sums the numbers in a list up until it finds a number that is smaller than or equal to 0 in the list. In this case, it sums up 3, 2 and 6.

Question 4

What is the output of the following code snippet? Type Error if it results in an error. Type Infinite if it ends up in an infinite loop.

verbs = ["eat", "study", "sleep", "repeat"] 
for verb in verbs:
    print(verb + "ing")

eating studying sleeping repeating
Explanation:

This piece of code adds the suffix "-ing" to the verbs in the list, and prints each of them out.

Question 5

What is the output of the following code snippet? Type Error if it results in an error. Type Infinite if it ends up in an infinite loop.

matrix = [[1, 0, 2], [3, 1, -4], [2, -2, 2], [1, 3, 2]] 
total = 0
for row in matrix:
    row_total = 0
    for cell in row:
        row_total += cell
    print(row_total)

    total += row_total
print(total)

3 0 2 6 11
Explanation:

Here is an example of a nested for loop in action. This is useful to iterate over a nested list, for example a matrix. This piece of code sums the numbers in each row of the matrix and prints it out. At the end, it also prints out the sum of all values in the matrix.