Sometimes you need to do repetitive tasks. Loops are the way to make your life easier.
Let number = 1
and you would like to add 1 until you reach 10 and each time print the value of the variable number to the screen. You could do it explicitly:
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
Or 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
The while
loop is useful if you want 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. Note also that in Python the task(s) to be done in the loop need to be indented.
'%d' % number
is an example of string formatting, in this case we're '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 convineint.
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) introduced f-string (format-string,f""
or f''
), which are an extremely convenient for string formatting:
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
Try what happens in the above example if you remove the colon or don't use indentation.
# Exercise 3.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.
If you already know how many times you want to execute a set of tasks, for loops are better suited.
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.")
Note that the range goes till 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 both 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
# There are other (easier) ways of going about this, e.g. the numpy library provides a function for this:
import numpy as np
np.dot(A, B)
# But this exercise demonstrates how we can use nested loops!
If you want to loop over a range of numbers, you can loop over range
. range(start, stop)
allow to define a [start, stop)
range. 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)