Let’s do some loops!

The general format is

For (single item of range) in range:
do stuff

Note the colon and the tab in the next line here too! Just like ‘if’ code.

  1. Type and run

cousinsAge = [16, 19, 19, 22, 23, 27, 27, 33, 35, 40]

for age in cousinsAge:
print(age)

Note the ‘age’ variable in the for loop. It is a loop variable that takes turn to contain each variable in the list as we loop through it

It is not the index like is C++, or a loop variable that only exists in a loop. It is true that its existence start with the for loop call – but if you print it later outside the loop you will notice that it quietly continues to exist holding the last value it captured (in the last iteration)

We can use any variable name instead of age. Let’s do a bit more of the same/similar thing – so that we understand.

  1. Type and run

for eachItem in cousinsAge:
print(“I have a %d-year-old cousin” %eachItem)

  1. The range doesn’t have to be a list of numbers, it can be a list of strings too!

Type and run

shoppingList = [‘ladyfingers’,’peas’, ‘onions’, ‘beef’, ‘jam’, ‘custard’, ‘bananas’, ‘whipped cream’, ‘raspberries’]

print(“To make the Thanksgiving Trifle Rachel made in Friends, I need the following: “)
for ingredient in shoppingList:
print(ingredient)