Sometimes when programming you might need to do repetitive tasks. For example, doing a given operation with an increasingly larger number.
Python offers loops as a way to make your life easier, and your code much smaller.
Assume number = 1
and you would like to add 1 until you reach 10. At each incrementation of number
you want to print the value of the variable number
to the screen. You could do it explicitly in the following manner:
number = 1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
print("number is equal to %d now." % number)
number +=1
This will easily become tedious as the number of increments increases. Instead you can save yourself some time and just program this as a loop:
number = 1
while number <= 10:
print("number is equal to %d now." % number)
number += 1
print("End of loop")
The while
loop is a useful construct which allows you to repeat a task while a certain statement is True
.
Here, this statement is number <= 10
.
The colon (:
) after the statement marks the beginning of the task(s) that are to be performed in the loop.
Once the statement becomes False
, the loop will stop being executed and the code will move on to its next section (in this case we print "End of loop").
Important note: As you can see from the code above, the task(s) to be done in the loop are indented. Indentation is how python determines if a block of code belongs to a given method statement.
For example, in the above code the presence of an indentation for:
print("number is equal to %d now." % number)
number += 1
Means that they belong to the while
statement.
However, since the:
print("End of loop")
does not have indentation, it does not get executed as part of the while
statement.
If the code was instead changed to indent the second print
statement, you would see that it would be executed at every iteration of the while
loop.
number = 1
while number <= 10:
print("number is equal to %d now." % number)
number += 1
print("End of loop")
'%d' % number
is an example of string formatting, in this case we are 'inserting' the value of variables into a string (use %d
for a number and %s
for a string). If you want to insert multiple variables, you can use e.g.: '%d %s' % (num, str)
. This is 'old-style' formatting; you can also use the 'new-style' formatting: '{} {}'.format(var1, var2)
. The new-style formatting lets us index our entries, which can be convenient.
print('This is %d example of a formatted %s' % (1, 'string'))
print ('This is the {}nd example of a formatted {}.'.format(2, 'string'))
# indexing with new-style
print('This is the {A} thing, here is the {B}, the {C}, and now the {A} again'.format(A='first', C='third', B='second'))
Recent versions of Python (from 3.6 onwards) have introduced a cleaner formatting method named f-strings (format-string,f""
or f''
). These are an extremely convenient for string formatting:
x = 1
print(f"'x' is of type {type(x)} and contains the value {x}")
Thus, by prepending our string with the letter f
, we can use variables and valid Python expressions within {}
. In the rest of the course we will prefer this new formatting style since it greatly improves readability and we strongly recommend the use of f-strings over other types of formatting
See what happens in the above example if you remove the colon or don't use indentation.
# Exercise 3.1.1
A problem with while
loops can be that eventually the condition under which they run is always True
and then they run forever. Without the line "number += 1" in the above example, the loop would run forever and always print "number is equal to 1 now." to the screen. Therefore, it is important to make sure that while
loops terminate at some stage.
While
statments are particularly useful when you are interating over a task an unknown number of times. An example of this would be if you are iteratively solving an equation for a given input until you reach a convergence limit.
However, if you already know how many times you want to execute a set of tasks, for
loops are better suited.
For loops take an iterator statment and loops over it until the iteration is exhausted.
To demonstrate this, you can equally write the above example as a for
loop:
for number in range (1,11):
print(f"number is equal to {number} now.")
Here number in range (1,11)
is the iterator statement which generates values of number
which progressively increase from 1 to 10 as the for loop is executed.
Note: the range goes to 11, but the loop stops at 10. This is something where Python is not very intuitive. If you define ranges, Python will not include the last value of your range. Since number is an integer here, the last integer before 11 is 10.
Use either a while
loop or a for
loop to print out the first 10 entries in the 6 times table, i.e.:
# Exercise 3.2.1
You can also use loops within loops - as many as you like. Just keep good track using indentations!
Use nested loops to calculate the matrix product of the two matrices:
\begin{bmatrix} 1 & 2 \\ 3 & 4 \end{bmatrix}
and
\begin{bmatrix} -3 & 1 \\ 4 & -2 \end{bmatrix}
Note: You can define each matrix as a numpy array (see section 10). You might want to work through section 10 first and then come back and try this exercise.
# Exercise 3.2.2
import numpy as np
As shown above, if you want to loop over a range of numbers, you can loop over range
. range
can be called with the arguments (start, stop)
in the manner range(start,stop)
. Here values will be assigned starting with the value of start
and ending with the value of stop - 1
. If start
is omitted, start=0
is assumed:
for i in range(5):
print(i)
for i in range(-5, 5):
print(i)
The range
function accepts a third argument that allows to modify the step size (default 1
). The full signature of range
is therefore range(start, stop, step)
.
for i in range(-5, 5, 2):
print(i)
In this section, we have covered:
while
loop construct.for
loop construct.range
to generate numbers over a given range.