Lecture 12 Iterations

1. The 'while' statement

Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly
Here is what countdown looks like with a while statement:

2. Tables
One of the things loops are good for is generating tabular data.

We can test if 'math.log()' is calculating the natural log: we put 'math.e' there as the natural log constant, and we got all the '1's in the results.
Don't forget to import the 'math' package if you did do this before.

If you want to find the log for base 2:

Or an alternative way:
Since we know:

So the alternative way to get log base 2 is:

This is verified when x=2, the result is 1.

3. The 'for loop'
Using an index to traverse a set of values is so common that Python provides an alternative, simpler syntax - the for loop:

One more example:
To print out all the letters in 'fruit' one by one, you can use a 'while loop':

Or a 'for loop':

The 'for loop' in Python has the index running on the back-end.

4. Looping and counting
The following program counts the number of times the letter 'a' appears in a string:


1. The value of pi can be approximated by:

Wriet a script (must use the 'while loop') with a user-defined function which asks the user to input the number of iterations (n), then computes the expression. The larger the number of iterations, the closer the result should be to pi. Print out the final result by calling the function. (You may want to force the input into an 'int' varable)

2. Repeat the task above using the 'for loop' instead of the 'while loop'.