First let's write a loop and considering the equivalent code.
for number in [2, 3, 5]:
print(number)
print(2)
print(3)
print(5)
We can see that the loop we have written:
for number in [2, 3, 5]:
print(number)
produces the same output as explicitly print the numbers, 2
, 3
and 5
.
But what is the loop actually doing and what are its principle features?
[2, 3, 5]
is the set of values that the loop is being run on.print(number)
, specifies what to do for each value in the collection.number
, changes with each iteration in the loop taking the values specified by the collectionfor number in [2, 3, 5]
Python recognises that we have made a mistake, tells us that there is a SyntaxError: invalid syntax
and also uses the up arrow to point to where in the line it thinks there is something missing.
If we forget to indent the body then Python does an even better job with helping us:
for number in [2, 3, 5]:
print(number)
Python flags the mistake with the IndentationError: expected an indented block
and the up arrow points to where Python expects the indented body of the loop to begin.
Finally, if you indent by mistake Python will also recognise this and let you know:
name = "James"
print("Hello", james)
The body of a loop is not restricted to a single line:
primes = [2, 3, 5]
for p in primes:
squared = p ** 2
cubed = p ** 3
print(p, squared, cubed)
The three lines of code that make up the body are all executed at every iteration of the loop. We have also introduced a new operator **
- this isn't a typo but as you may have deduced from the context, it is the power operator.
Note however that if we you multiple lines of code in the body and you forget to indent the last one, Python cannot know which lines you meant to be part of the body and which weren't:
primes = [2, 3, 5]
for p in primes:
squared = p ** 2
cubed = p ** 3
print(p, squared, cubed)
The final line of what was meant to be the body is now only executed after the loop has completed, so it only call the last line, once, with the final value that the loop variable takes.
range
to specify the collection¶If we have three values in the collection and they are prime numbers then writing them out isn't too difficult, but what if we want to execute some code hundreds or thousands of times.
This is the real power of loops and Python provides the function range
to help us out.
Consider the following, which accumulates the values (number + 1)
in total
.
# Sum the first 10 integers
total = 0
for number in range(10):
total = total + (number + 1)
print(total)
range(integer)
has been used to create the collection that our loop variable, number
is looping over but what does range
do?
We can investigate by printing it and finding out its type:
print( "Range(10) displays as:", range(10), "and is of type:",type( range(10) ))
This is not hugely informative, though our range(10)
has been expanded to range(0,10)
.
What we need to know is that Python effectively treats range
as if it were a list.
As with other type
s we can use list
to turn one type
into another:
print( "Range(10) displays as:", range(10))
print("but we can think of it as a list:", list( range(10) ))
We can now see that range(10)
is treated as a list of the first 10 integers, if we assume that we need to start counting at 0 because were are programming in Python.
It also explains why we need to add 1
to number each time we iterate the loop, because in Python we start counting from 0
but when we ask to sum the first N
integers we expect to start from 1
.
We can also demonstrate the value of the loop structure by changing our original sum:
# Sum the first 10,000 integers
total = 0
for number in range(10000):
total = total + (number + 1)
print(total)
One way in which loops become useful for us, is when we use them to loop over a dataset and perform some analysis. Let's return to our list of pressures in the previous episode and calculate the mean. In programming there are many ways of performing a given task and we will consider an example.
pressures = [0.273, 0.275, 0.277, 0.275, 0.276]
num_pressures = len(pressures)
sum_pressures = 0.0
for index in range( num_pressures ):
sum_pressures = sum_pressures + pressures[ index ]
mean_pressure = sum_pressures / num_pressures
print("The mean pressure is:", mean_pressure)