Loops and iterative thinking

3. Loops and iterative thinking

A loop is a programming structure that repeats a code, either a certain number of times or until a criterion is reached.

Loops allow us to take advantage of the computer’s ability to quickly perform operations multiple times. Using loops, for example, the computer can find the number 10 531 in the Fibonacci sequence in less than one second, or it can calculate the solution to an analytically insoluble equation by repeating the same operation 10000 times. Loops are the most important and useful programming structure we have.

Here we will look at some basic examples to get you comfortable with how loops in Python works. Do both exercises in the tabs, and do the “discussion” exercises last.

Look at these three program lines. When it says even number = even number + 2, the program will calculate the right side of the equals sign first and put it into the left side afterwards.

What is the value of the variable even after the three lines?

even_number = 0
even_number = even_number + 2
even_number = even_number + 2

Repeating code like this can be tiresome. Enter the loops! Using a counter i we can for example repeat this operation 5 times:

even_number = 0

for i in range(5):
    even_number = even_number + 2

This is called a for-loop, which is a counting-loop that iterates (goes through) numbers in an interval. The command range(1000) means that we create a variable that will go through an interval specified in parentheses. If we write range(5), the interval becomes [0, 1, 2, 3, 4], that is, from 0 to - but not including - 5. If we write range(2,6), the interval becomes [2, 3, 4, 5]. If we add another argument to the range function, we can specify the step: range(2,11,2) gives the numbers [2,4,6,8,10]. Each time the loop code is repeated, the variable i, which we call a “count variable”, gets the next value in the interval. The loop is thus repeated five times in the code above. The indented code in the loop is repeated each time the loop runs.

Try to make a loop that prints the square root of the variable i for every odd number of i in the interval [0,25]

Now we are going to make a program that adds together the first five even numbers. What kind of variables do you need? How do you solve this by using loops? Start by creating a pseudocode where you focus on the logic of problem solving.

Now you can make a program from the pseudocode you made above. We have made some lines of code to get you started:

A good way to check if the loop works and does what it should, is to write a table with the values of all the variables at all steps in the loop:

i

even_number

the_sum

0

2

2

1

4

6

2

6

12

3

8

20

4

10

30

This is called a “looping table”. Our counting variable i shows the step in the loop, while the other two columns are filled in by manually calculating what is in the loop. The first time the loop runs, i = 0. Then even_number = even_number + 2 = 0 + 2. The variable the_sum becomes equal to the previous the_sum + even_number: the_sum = the_sum + even_number = 0 + 2 = 2. The next time the loop runs, i = 1. Thus even_number = 2 + 2 = 4, and the_sum = 2 + 4 = 6. This is repeated until i = 4.

NB: When we are updating the variables above, we write for example even_number = even_number + 2. There is a way to write this shorter: even_number + = 2. The short form means the same thing, but for pedagogical reasons it is a good idea to start with writing the full form: even_number = even_number + 2. However, it is useful to know that the short form exists, and many students will probably use this eventually.

Loops make possible a new way of thinking. Several students struggle with manipulating, remembering and understanding mathematical formulas. Loops can be a way of doing mathematics and science without focusing too much on symbolic manipulation. For example, the example where you calculated sums can be generalized to almost all sums. Do you need to find the 100 000th number in the Fibbonacci sequence or calculate the sum of an infinite geometric series - thinking in loops will help you. Instead of finding special formulas for the solutions, one can solve the problems iteratively, that is by thinking in steps. Stepwise, iterative thinking can be helpful for students to understand dynamic phenomena.

Using mathematical models and calculating the next value based on the previous value can feel more intuitive than solving formulas. By using loops you can solve rate laws in chemistry, population dynamics equations i biology or Newtons laws in physics. If you have an initial condition and a model describing the change of the system, you can use a stepwise, iterative process to find out how the system evolves in time. Every student can learn something from this, and maybe they can understand the concepts behind the science better.

When using loops, it is also easier to change the premises for our models. We can also change our models to be non-continous, since we can alter them at discrete steps. Let us take bacterial growth as an example. It is common to model bacterial growth as a continuous exponential function. If we start with 100 bacteria and estimate that the growth is 20 percent per hour, we can find out how many bacteria we have after t hours by using the following function:

\[ f(t) = 100\cdot 1.20^t \]

If t = 30, we can calculate that we have 23 737 bacteria after 30 hours (we round down to the nearest whole bacterium). We can create a program that does exactly the same thing and gives the same result:

{code-block} python
B0 = 100
B = B0
hourse = 30
growth_factor = 1.20

for i in range(hours):
    B = B*growth_factor

print("The number of bateria is:", int(B))

This program does the same thing as putting t = 30 into the function above. But what if we introduce a variable for growth factor? The conditions under which the bacteria live may change due to temperature, access to nutrients or the like. When we program, we can enter such assumptions and easily change them. In this way, programming provides more opportunities than continuous functions to study and experiment with dynamic systems. The same applies to situations such as variable interest rates in the bank or changes in a physical or chemical system. In such situations, programming is really useful! Click on the drop-down menu below to see an example of such a program. We will also look at savings and interest rates in activity 1 below.

Discussion

“Thinking in loops” (iterative thinking) can be a challenge in the beginning. Loops are useful for a lot, so it is well worth practicing.

  • Can you think of any mathematical or scientific problems that can be solved with loops?

  • Can loop tables be an effective tool in your teaching? If so, how will you use them?