Iteration

Iteration is a form of repetition, i.e. repeating the same staments over and over until some terminating condition becomes true.

We saw another form of repetition when we looked at recursion. Now we shall focus on iteration.

Python offers the while and for loops for iterating over statements. They are called loops because execution flows back to the loop's header when the last statement in the body is exeecuted.

The while statement

Let's look at the while statement first with an example.

The while starts off with a condition (count > 0) and as long as the condition is true, the body of the while will execute.

Inside the body we print the count and decrement it by 1.

As the decrement statement is the last statement in the body, we loop back to the header for another test.

When the condition eventually becomes false (count == 0) the while ends and we print Blastoff!.

Note: Make sure that inside the body you change the variables in the condtion, so that it eventually becomes false, else you will have an infinite loop.

Since the condition is evaluated first before the body is executed, the body may never execute if the condition is false.

Square Roots

Many mathematical functions you find in any math library are computed by some iterative method. For instance to compute the square root of $a$, $sqrt(a)$ you can use Newton's method:

$r = \frac{x + a / x}{2}$

where $x$ is an initial estimate for the root and $r$ is the estimated root.

The for statement

While offers another construct for repeating code, called the if statement. We will see this again when we cover iterating sequences.

Let's look at an example using two powerful features, the in and range.

The range(start, stop, step) function can accept three arguments:

start: the starting value in the generated sequence stop: the first value not in the generated sequence step: the value between each generated value

The function basically returns a sequence starting with start and ending at stop - step. Each number is a step value from the previous.

break

The break statement is often used to exit from a loop early.

Here is a quick example to demonstrate its use.

Let's look at another example using the break statement.

The program will read in integer numbers and sum them up. If a -1 is entered the loop will end and the sum will then be displayed.

The output shown resulted from the input: 1 2 3 -1

Continue

The continue statement skips the rest of the body and begins an new iteration.

Here is a quick example to demonstrate its use.

Practice problems

Create a separate Python source file (.py) in VSC to complete each exercise.


p1: mysqrt.py

Use the squareRoot(a) function from above and the function named test_square_root() that prints a table like this:

a     squareRoot(a)        math.sqrt(a)         diff                
----- -------------------- -------------------- --------------------
1.0   1.0                  1.0                  0.0                 
2.0   1.414213562373095    1.4142135623730951   2.220446049250313e-16
3.0   1.7320508075688772   1.7320508075688772   0.0                 
4.0   2.0                  2.0                  0.0                 
5.0   2.23606797749979     2.23606797749979     0.0                 
6.0   2.449489742783178    2.449489742783178    0.0                 
7.0   2.6457513110645907   2.6457513110645907   0.0                 
8.0   2.82842712474619     2.8284271247461903   4.440892098500626e-16
9.0   3.0                  3.0                  0.0

The first column is a number, a; the secondd column is the square root of a computed with squareRoot(); the third column is the square root computed by math.sqrt(); the fourth column is the absolute value of the difference between the two estimates.


p2.eval.py

The built-in function eval() takes a string and evaluates it using the Python interpreter. For example:

Write a function eval_loop() that iteratively prompts the user, takes the resulting input and evaluates it using eval() and prints the result.

It should continue until the user enters 'done', and then return the value of the last expression it evaluated.


p3 estimatePi.py

The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of $\displaystyle\frac{1}{\pi}$:

$\displaystyle\frac{1}{\pi} = \frac{2\sqrt{2}}{9801}\sum_{k=0}^{\infty} \frac{(4k)!(1103 + 26390k)}{(k!)^{4}396^{4k}}$

Write a function called estimatePi() that uses this formula to compute and return an estimate of $\pi$. It should use a while loop to compute terms of the summation until the last term is smaller than 1e-15 (which is Python notation for $10^{-15}$). You can check the result by comparing it to math.pi.

[Functions Return] [TOC] [Strings]