Card 10: Iterating

Module 4: Data Structures

1 The Hook

Imagine a teacher taking the register.

She doesn't say "Everyone say 'Here' at once!"
She goes through the list, one by one.

This is Iteration. We loop through a list and handle each item individually.

2 Worked Example

Printing a menu.

menu = ["Burger", "Chips", "Soda"]
for item in menu: # 'item' becomes "Burger", then "Chips"...
print(item)

PREDICT

What happens to the numbers?

nums = [1, 2, 3]
for x in nums:
  print(x * 10)

Interactive Editor

> _
BRONZE (MODIFY)

🥉 Colour Palette

1. Create a list of 3 colours: ['Red', 'Blue', 'Green'].
2. Loop through them.
3. Print "I like " + colour.

> _
SILVER (FIX)

🥈 Missing Colon

This code fails because of a syntax error.
1. Fix the error (Add the :).
2. Make sure it prints "Code is Fun" 3 times.

> _
GOLD (MAKE)

🥇 Average Machine

1. Create a list: [10, 20, 30, 40].
2. Create a total (0).
3. Loop and sum them up.
4. Calculate average: total / 4.
5. Print the average (25.0).

> _