7. Iteration
Just a quick introduction
print(1+2+3)
1+2+3+...+10? Not that difficult.
How about 1+2+3+...+10000?
In this case, we need iterations.
The first type of iteration is for
loop. Recall how we drew a square using a for loop:
for i in range(4):
leo.fd(100)
leo.lt(90)
for x in ...
is to take every element into variable x, ane then execute the following block.
Exercise 01
-
Calculate the sum of integers from 1 to 10.
-
Calculate the sum of integers from 1 to 1000. (hint: we need to use
range()
.) -
Calculate the sum of all the odd numbers from 1 to 1000. (hint: check out range() function in Python documentation.) How about all the even numbers?
def countdown(n):
while n > 0:
print(n)
n = n - 1
print('Blastoff!')
You can almost read the while statement as if it were English. It means, “While n is greater than 0, display the value of n and then decrement n. When you get to 0, display the word Blastoff!”
More formally, here is the flow of execution for a while statement:
- Determine whether the condition is true or false.
- If false, exit the while statement and continue execution at the next statement.
- If the condition is true, run the body and then go back to step 1.
iteration = 0
count = 0
while iteration < 5:
# the variable 'letter' in the loop stands for every
# character, including spaces and commas!
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
1. What is the value of the variable count that is printed out (at the print statement) on iteration 0?
2. What is the value of the variable count that is printed out (at the print statement) on iteration 1?
3. What is the value of the variable count that is printed out (at the print statement) on iteration 2?
4. What is the value of the variable count that is printed out (at the print statement) on iteration 3?
5. What is the value of the variable count that is printed out (at the print statement) on iteration 4?
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
1. What is the value of the variable count that is printed out (at the print statement) on iteration 0?
2. What is the value of the variable count that is printed out (at the print statement) on iteration 1?
3. What is the value of the variable count that is printed out (at the print statement) on iteration 2?
4. What is the value of the variable count that is printed out (at the print statement) on iteration 3?
5. What is the value of the variable count that is printed out (at the print statement) on iteration 4?
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
if iteration % 2 == 0:
break
print("Iteration " + str(iteration) + "; count is: " + str(count))
iteration += 1
1. How many times will the print statement be executed?
2. What is the largest value of the variable iteration that will be printed out (at the print statement)?
3. What is the largest value of the variable count that will be printed out (at the print statement)?
4. What is the smallest value of the variable count that will be printed out (at the print statement)?
2, Using while
rewrite all the loops in Exercise 01.
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
This way of writing while loops is common because you can check the condition anywhere in the loop (not just at the top) and you can express the stop condition affirmatively (“stop when this happens”) rather than negatively (“keep going until that happens”).
Q. What happens in the following program?
mysum = 0
for i in range(5, 11, 2):
mysum += i
if mysum == 5:
break
print(mysum)
Case study: Square roots
Loops are often used in programs that compute numerical results by starting with an approximate answer and iteratively improving it.
For example, one way of computing square roots is Newton’s method. Suppose that you want to know the square root of a
. If you start with almost any estimate, x
, you can compute a better estimate with the following formula:
$$y=\frac{x+a/x}{2}$$
For example, if a
is 4 and x
is 3:
a = 4
x = 3
y = (x + a/x) / 2
print(y)
The result is closer to the correct answer (√4 = 2). If we repeat the process with the new estimate, it gets even closer:
x = y
y = (x + a/x) / 2
print(y)
After a few more updates, the estimate is almost exact:
x = y
y = (x + a/x) / 2
print(y)
x = y
y = (x + a/x) / 2
print(y)
In general we don’t know ahead of time how many steps it takes to get to the right answer, but we know when we get there because the estimate stops changing:
x = y
y = (x + a/x) / 2
print(y)
x = y
y = (x + a/x) / 2
print(y)
When y == x, we can stop. Here is a loop that starts with an initial estimate, x, and improves it until it stops changing:
while True:
print(x)
y = (x + a/x) / 2
if y == x:
break
x = y
For most values of a this works fine, but in general it is dangerous to test float equality. Floating-point values are only approximately right: most rational numbers, like 1/3, and irrational numbers, like √2, can’t be represented exactly with a float.
Rather than checking whether x
and y
are exactly equal, it is safer to use the built-in function abs to compute the absolute value, or magnitude, of the difference between them:
if abs(y-x) < epsilon:
break
Where epsilon
has a value like 0.0000001 that determines how close is close enough.
a mysqrt(a) math.sqrt(a) diff
- --------- ------------ ----
1.0 1.0 1.0 0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0 2.0 0.0
5.0 2.2360679775 2.2360679775 0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0 3.0 0.0
The first column is a number, a; the second column is the square root of a computed with mysqrt
; 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.