13 Iteration – Loops – For


A for loop[2] is used to iterate[3] over a known number of items or a list.

It is used when you know how many times the loop will need[4] to run.

The loop below will print out all of the items in a list.

The indented code will run for each item in the list.

characters = ["Mario", "Sonic", "Crash"]
for x in characters:
  print(x)

If you want to run a loop a set number of times we use the range[5]() function[1]

There are two different range functions. One takes one argument.

This number is exclusive this means that we don’t include this number and we start at 0.

range(6) will start at 0 and finish at 5.

for x in range(6):
  print(x)

There is also a two argument version which includes the first value and excludes the second value.

range(4, 10) will start at 4 and finish at 9

for x in range(4, 10):
  print(x)

For more information about Python for loops look on W3 Schools.

Terms definitions
1. function. A named section of a computer program that performs a specific task. Functions help make code more efficient and reusable. They may take input parameters and produce output.
2. loop. A sequence of instructions in a program repeated until a certain condition is reached: * with a “for loop”, the instructions are repeated a certain number of times * with a “while” loop, the instructions are repeated until a given condition becomes false * with a “forever loop” (also known as an “infinite” or “endless” […]
3. iterate. A sequence of instructions in a program repeated until a certain condition is reached: with a “for loop”, the instructions are repeated a certain number of times with a “while” loop, the instructions are repeated until a given condition becomes false with a “forever loop” (also known as an “infinite” or “endless” loop), the instructions […]
4. need. An identified requirement of a person, group, or environment. A need is identified from an issue and sits within a context. Technological practice can be undertaken in an attempt to meet an identified need.
5. range. A selection of items. When asked in the context of an achievement standard it means at least three. In spreadsheets range is a way of selecting a group of cells. A colon is used to separate the starting and ending cells. e.g. B4:F10