1.3. The for loop#

The thing computers are really good at is repeating a calculation lots of times

One way to do this is using a loop

Here we meet the for loop (there is also such thing as a while loop which we will meet later)

Set up Python libraries#

As usual, run the code cell below to import the relevant Python libraries

# Set-up Python libraries - you need to run this but you don't need to change it
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as stats
import pandas 
import seaborn as sns
sns.set_theme()

Example: “hello, hello, hello”#

Say we want to repeat something a few times, like saying hello

We can get the computer to do this using a for loop

for i in range(3):
    print("i = " + str(i))
    print("hello!")
i = 0
hello!
i = 1
hello!
i = 2
hello!
  • See if you can change the code to say "hello" five times

We can also use the for loop to do the same operation for every member of a list:

friends = ['Alan','Barry','Craig']
print('number of friends is ' + str(len(friends)))


for i in range(len(friends)):
    print("i = " + str(i))
    print("Hello " + friends[i] + "!")
number of friends is 3
i = 0
Hello Alan!
i = 1
Hello Barry!
i = 2
Hello Craig!
  • What does len(friends) do? (Hint - check 'number of friends is...')
  • What does range(len(friends)) do? (Hint - check what range(3) did above

Exercise: when to eat shellfish#

It is said that you should only eat shellfish in months that don’t have “r” in the name.

We can check whether a month has an r in the name using the test in, which returns True or False:

month = "January"
"r" in month
True
month = "May"
"r" in month
False

We can set up an if statement to print different statements depending on whether there is an r in the name of the month

month = "August"

if ("r" in month):
    print('Don\'t eat shellfish in ' + month)
else:
    print('Do eat shellfish in ' + month)   
Do eat shellfish in August

Now can you make a for loop that checks every month and prints a sentence about whether to eat shellfish, as in the if statement above?

months=['January','February','March','April','May','June',
        'July','August','September','October','November','Decemeber']

for i in range(12): # complete the code
    if ("r" in months[i]):
        print('Don\'t eat shellfish in ' + months[i])
    else:
        print('Do eat shellfish in ' + months[i]) 
        
Don't eat shellfish in January
Don't eat shellfish in February
Don't eat shellfish in March
Don't eat shellfish in April
Do eat shellfish in May
Do eat shellfish in June
Do eat shellfish in July
Do eat shellfish in August
Don't eat shellfish in September
Don't eat shellfish in October
Don't eat shellfish in November
Don't eat shellfish in Decemeber

Example: adding up numbers#

Say we want to add up all the numbers from 1 to 10.

We could do it like this:

s = 1+2+3+4+5+6+7+8+9+10
print('sum = ' + str(s))
sum = 55

… but that would get annoying if we wanted to add up, say, the numbers from 1 to 100.

Let’s try another way.

First let’s get an array with the numbers 1-10 in it using the numpy function np.arange

numbers = np.arange(start=1, stop=10, step=1)
print(numbers)
[1 2 3 4 5 6 7 8 9]

Oops, I forgot in Python the upper bound of the range is always left out - so if I want to stop at 10 (rather than 9) I need to do this:

numbers = np.arange(start=1, stop=10+1, step=1)
print(numbers)
[ 1  2  3  4  5  6  7  8  9 10]

Loop: add one number at a time#

Let’s create a variable called s which is the sum of the numbers.

Initially, s is zero

s = 0

Then we can add each element of our array numbers in turn

s = 0
s = s+numbers[0] # remember the first number in the list is indexed '0' not '1'!
print(s)
1

and the rest…

s = 0
s = s+numbers[0] 
print(s)
s = s+numbers[1] 
print(s)
s = s+numbers[2] 
print(s)
s = s+numbers[3] 
print(s)
s = s+numbers[4] 
print(s)
s = s+numbers[5] 
print(s)
s = s+numbers[6] 
print(s)
s = s+numbers[7] 
print(s)
s = s+numbers[8] 
print(s)
s = s+numbers[9] # remember the last one is in position 9, not 10!
print(s)
1
3
6
10
15
21
28
36
45
55

Ooph, that was cumbersome!

We an avoid typing the commands every time by doing a loop

s=0
numbers = np.arange(start=1, stop=10+1, step=1)
for i in range(len(numbers)):
    s=s+numbers[i]
    print(s)
1
3
6
10
15
21
28
36
45
55

We don’t even need to print s out every time, just at the end

We signal the end of the loop by the end of the indenting:

s=0
numbers = np.arange(start=1, stop=10+1, step=1)
for i in range(len(numbers)):
    s=s+numbers[i]
    
print(s)
55

We can make our loop generalizable using a variable $n$ for the number up to which we are summing integers:

n=10
s=0
numbers = np.arange(start=1, stop=n+1, step=1)
for i in range(len(numbers)):
    s=s+numbers[i]
    
print(s)
55

Exercises:#

  • Can you edit the loop above so it sums the numbers to n=100 ?
  • What about obtaining the sum of the numbers [0.1, 0.2, 0.3 ..... 0.9, 1.0]?

Aside#

We can actually work out the sum of the numbers to $n$ using the formula

$s_n = \frac{n(n+1)}{2}$

You can think of it as a series of 101 pairs that each add to 100:

  • 0+100 = 100
  • 1+99 = 100
  • 2+98 = 100
  • 3+97 = 100
  • 49+51 = 100
  • 50+50 = 100

This formula has been known since the time of Pythagoras.

One charming story about the great mathematician Euler is that when he was in infant school, the master gave the task of summing numbers to 100 to keep the children quiet for a while. Within a few seconds Euler was at his desk with the answer, having immediately perceived that the solution above could be used.

Example: Fibonacci Sequence#

The Fibonacci Sequence is a sequence of numbers that begins [0,1,…] and continues by adding together the two previous numbers such that

$$ x_i = x_{i-1} + x_{i-2} $$

The sequence begins [0, 1, 1, 2, 3, 5, 8, 13….. ] and goes on forever.

You can find some fun facts about the Fibonacci sequence here:

Let’s make a for loop to calculate the first 10 elements of the Fibonacci sequence

n = 10 # number of elements to calculate
fibonaccis = np.empty(n) 

# get the sequence started
fibonaccis[0] = 0
fibonaccis[1] = 1

for i in range(2,n): # start in place 2 as we already set the first two elements of the sequence (places 0 and 1)
    fibonaccis[i] = # your code here to calculate the ith Fibonacci number
    
plt.plot(fibonaccis,'.-')
plt.xlabel('$i$')
plt.ylabel('$x_i$')
  Cell In[17], line 9
    fibonaccis[i] = # your code here to calculate the ith Fibonacci number
                    ^
SyntaxError: invalid syntax