manyspikes

Loops

What if we would like to execute a given part of the code multiple times? This can be achieved using loops, which can be implemented via two distinct mechanisms: for loops and while loops.

Let's start by looking at a for loop:

letters = ["a", "b", "c"] for letter in letters: print(letter)

This will print the letters a, b and c. But let's go through the example step-by-step.

The for loop executes the following steps:

  1. Take an item from a collection of elements (in this case, the list letters)
  2. Assigns the item to a loop variable (in this case, letter)
  3. Executes the code inside the for loop (in this case, print(letter)).
  4. Moves to the next item and repeats steps 2-4 until no items are left.

Each turn is referred to as one iteration.

In the example above we iterated over a list, but Python will happily iterate over other types like tuples, sets, and dictionaries. The only requirement is that the type at hand exposes an iterator, but we will discuss this in more detail in a later module.

While loops are another option to achieve a similar effect. Below we demonstrate how to implement the logic in the for loop above, but now using a while loop:

letters = ["a", "b", "c"] n_letters = len(letters) idx = 0 while idx < n_letters: print(letters[idx]) idx += 1 # this is equivalent to idx = idx + 1

While loops execute some logic until a given condition evaluates to False. Here we create a variable called idx which starts by being 0 and is incremented by 1 at every iteration of the while loop. The while loop condition is checked at every iteration. In the 4th iteration, idx (which at that point is equal to 3) is no longer smaller than n_letters, so the while loop terminates.

In this particular case, the for syntax is much more succinct than the while loop alternative, but that is not always the case!