4.1. For loops#
If we want to repeat the execution of a set of commands a given number of times then we can use a for loop. The Python syntax for a for loop is
for variable in list:
commands to be executed
The for
declaration requires a loop variable
and a list
followed by a colon :
. The loop variable
takes on the value of the first element in list
and the commands in the indented lines below the for loop declaration are executed for this value. Then the loop variable
takes on the value of the second element in list
and the commands in the intended lines below are repeated for this value. The loop continues in this way for all of the elements in list
.
Create a Python file called 4_Loops.py and save it to your OneDrive folder. Enter the following code into your program.
# 4. Loops
# For loops
subjects = ["linear algebra", "programming", "calculus"]
for subject in subjects:
print(subject)
Run your program and your should see the following printed to the console.
linear algebra
programming skills
calculus
Here we created a list containing three subjects and then used a for loop to print each of the subjects. A very useful Python function is range()
that generates a list of numbers based on the start
, stop
and step
values (similar to the np.arange()
function). Enter the following code into your program.
print()
for i in range(5):
print(i)
Run your program and you should see the following added to the console.
0
1
2
3
4
4.1.1. A dummy loop variable#
Sometimes we want to repeat a set of commands a set number of times but the commands do not need the value of a loop variable. In these cases we can use an underscore _
for a loop variable.
For example, lets use a for loop to calculate the value of a base number raised to a power. Add the following code into your program
base = 2;
power = 10;
base_power = 1;
for _ in range(power):
base_power *= base
print(f"\n{base}^{power} = {base_power} \n")
Here we have calculated \(2^{10}\) using a for loop. Since we only need to multiply base
by itself power
times we don’t need a for loop variable.
Run your program and you should see the following added to the console.
2^10 = 1024
(Of course in this case its much easier to use 2 ** 10
)
4.1.2. The Fibonacci sequence#
To demonstrate how useful for loops are we will use one to generate the first \(n\) numbers of the Fibonacci sequence \(F_0, F_1, \ldots, F_n\) which is defined as
Lets write a program to create an array containing the first 20 Fibonacci numbers. Enter the following code into your program.
# The Fibonacci sequence
a, b = 0, 1
print(a)
print(b)
for _ in range(2, 20):
c = a + b
print(c)
a = b
b = c
Here we use two variables a
and b
to contain two successive Fibonacci numbers which are initialise to 0 and 1 respectively. We then use a for loop to loop through values from 2 to 19 since we already know the first two Fibonacci numbers. Inside the for loop we update calculate the next number in the sequence and print it out and update the values of a
and b
.
Run your program and your should see the following added to the console output.
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
Note
In the code used to print the Fibonacci numbers we used a third variable c
to temporarily store the next value in the sequence. Instead we could use Python’s ability to assign multiple variables on the same line which avoids using a third variable.
for _ in range(2, 20):
a, b = b, a + b
print(b)
4.1.3. Exercises#
Create a new Python file called 4_Loops_exercises.py and save it to your OneDrive folder. Use it to answer the following exercises.
Use a for loop to print “hello world” 10 times.
The factorial of a number \(n\) is denoted by \(n!\) and defined as the product of the numbers 1 to \(n\)
Use a for loop to calculate 52!, the number of ways a regular pack of cards can be shuffled.[1]
The series expansion of \(\sin(x)\) is
Use a for loop to compute \(\sin(\frac{\pi}{4}) \approx 0.707\) by summing this series up to the first 5 terms.
Hints: the following commands from the math
library may come in useful:
math.pi
returns the value of \(\pi\)math.factorial(n)
returns \(n!\)