For loops: exercises - SOLVED#

Exercise#

Try printing the numbers from 0 to 5, and from 1 to 12.

for n in range(0,6):
  print(n)

for n in range(1,13):
  print(n)
0
1
2
3
4
5
1
2
3
4
5
6
7
8
9
10
11
12

Exercise#

In the cell below, by using the for loop print all the integers from the interval \([-20,20]\). Remember to use range(a,b).

for n in range(-20,21):
  print(n)
-20
-19
-18
-17
-16
-15
-14
-13
-12
-11
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Guided exercise#

Let’s look at something a little more complex. A pen and paper may be useful here. Consider the following bit of code:

j = 5
for k in range(2, 6):
    j = j + k * (-1)**k

print(f"j  = {j}")
j  = 3

What is it doing? Could you predict (with pen and paper) what the value of j at the end was going to be. We currently have j=5 on the first line, consider if we had instead j=4 on the first line .. then what would the final value of j be?

To help with this let’s step through what will happen in the loop (when j=5 on the first line). The loop will loop over 4 values of k (first k=2, then k=3, then k=4, then k=5).

Before we enter the loop j has value 5. Then at each step

Step 1) k = 2, j = 5 + 2 * (-1)^2 = 5 + 2 = 7

Step 2) k = 3, j = 7 - 3 = 4

Step 3) k = 4, j = 4 + 4 = 8

Step 4) k = 5, j = 8 - 5 = 3

Exercise#

In the cell below, by using the for loop, calculate and print the following sum: $\( \sum_{i=1}^{n} i^2 = 1^2 + 2^2 + 3^2 + \ldots + n^2,\)\( where \)n=100$. (This means: loop over all numbers from 1 to 100, square each of them, and add them all together)

j = 0

for i in range(1,101):
  j = j + i**2

print(j)
338350

Exercise#

Look at the function defined below. Try to determine, on paper, exactly what it will return for some small values of n. Test that. Can you figure out what mathematical function this is calculating?

def mystery(n):
    """This function is a mystery"""
    y = 1
    for x in range(1, n+1):
        y = y*x
    return y
#This is the factorial function, with the initial value being zero factorial