Time for action – repeating instructions with loops
We can use the for
loop in the following ways:
Loop over an ordered sequence, such as a list, and print each item as follows:
>>> food = ['ham', 'egg', 'spam'] >>> for snack in food: ... print(snack) ... ham egg spam
And remember that, as always, indentation matters in Python. We loop over a range of values with the built-in
range()
orxrange()
functions. The latter function is slightly more efficient in certain cases. Loop over the numbers1-9
with a step of 2 as follows:>>> for i in range(1, 9, 2): ... print(i) ... 1 3 5 7
The start and step parameter of the
range()
function are optional with default values of1
. We can also prematurely end a loop. Loop over the numbers0-9
and break out of the loop when you reach3
:>>> for i in range(9): ... print(i) ... if i == 3: ... print('Three') ... break ... 0 1 2 3 Three
The loop stopped at
3
and we did not print the higher numbers. Instead of leaving the loop, we can also get out of the current iteration. Print the numbers0-4
, skipping3
as follows:>>> for i in range(5): ... if i == 3: ... print('Three') ... continue ... print(i) ... 0 1 2 Three 4
The last line in the loop was not executed when we reached
3
because of thecontinue
statement. In Python, thefor
loop can have anelse
statement attached to it. Add anelse
clause as follows:>>> for i in range(5): ... print(i) ... else: ... print(i, 'in else clause') ... 0 1 2 3 4 (4, 'in else clause')
Python executes the code in the
else
clause last. Python also has awhile
loop. I do not use it that much because thefor
loop is more useful in my opinion.
What just happened?
We learned how to repeat instructions in Python with loops. This section included the break
and continue
statements, which exit and continue looping.