Think Python/Iteration

Multiple assignment
As you may have discovered, it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to a new value (and stop referring to the old value).

The output of this program is 5 7, because the first time bruce is printed, its value is 5, and the second time, its value is 7. The comma at the end of the first print statement suppresses the newline, which is why both outputs appear on the same line.

Here is what multiple assignment looks like in a state diagram:



With multiple assignment it is especially important to distinguish between an assignment operation and a statement of equality. Because Python uses the equal sign (=) for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

First, equality is a symmetric relation and assignment is not. For example, in mathematics, if a = 7 then 7 = a</I>. But in Python, the statement <TT>a = 7</TT> is legal and <TT>7 = a</TT> is not.

Furthermore, in mathematics, a statement of equality is either true or false, for all time. If <I>a</I> = <I>b</I> now, then <I>a</I> will always equal <I>b</I>. In Python, an assignment statement can make two variables equal, but they don&#X2019;t have to stay that way:

The third line changes the value of <TT>a</TT> but does not change the value of <TT>b</TT>, so they are no longer equal.

Although multiple assignment is frequently helpful, you should use it with caution. If the values of variables change frequently, it can make the code difficult to read and debug.

Updating variables
One of the most common forms of multiple assignment is an update, where the new value of the variable depends on the old. This means &#X201C;get the current value of <TT>x</TT>, add one, and then update <TT>x</TT> with the new value.&#X201D;

If you try to update a variable that doesn&#X2019;t exist, you get an error, because Python evaluates the right side before it assigns a value to <TT>x</TT>: Before you can update a variable, you have to initialize it, usually with a simple assignment:

Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.

The <TT>while</TT> 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.

We have seen two programs, <TT>countdown</TT> and, that use recursion to perform repetition, which is also called iteration. Because iteration is so common, Python provides several language features to make it easier. One is the <TT>for</TT> statement we saw in Section&#XA0;4.2. We&#X2019;ll get back to that later.

Another is the <TT>while</TT> statement. Here is a version of <TT>countdown</TT> that uses a <TT>while</TT> statement: You can almost read the <TT>while</TT> statement as if it were English. It means, &#X201C;While <TT>n</TT> is greater than 0, display the value of <TT>n</TT> and then reduce the value of <TT>n</TT> by 1. When you get to 0, display the word <TT>Blastoff!</TT>&#X201D;

More formally, here is the flow of execution for a <TT>while</TT> statement:


 * Evaluate the condition, yielding <TT>True</TT> or <TT>False</TT>.
 * If the condition is false, exit the <TT>while</TT> statement and continue execution at the next statement.
 * If the condition is true, execute the body and then go back to step 1.

This type of flow is called a loop because the third step loops back around to the top.

The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever, which is called an infinite loop. An endless source of amusement for computer scientists is the observation that the directions on shampoo, &#X201C;Lather, rinse, repeat,&#X201D; are an infinite loop.

In the case of <TT>countdown</TT>, we can prove that the loop terminates because we know that the value of <TT>n</TT> is finite, and we can see that the value of <TT>n</TT> gets smaller each time through the loop, so eventually we have to get to 0. In other cases, it is not so easy to tell: The condition for this loop is <TT>n != 1</TT>, so the loop will continue until <TT>n</TT> is <TT>1</TT>, which makes the condition false.

Each time through the loop, the program outputs the value of <TT>n</TT> and then checks whether it is even or odd. If it is even, <TT>n</TT> is divided by 2. If it is odd, the value of <TT>n</TT> is replaced with <TT>n*3+1</TT>. For example, if the argument passed to <TT>sequence</TT> is 3, the resulting sequence is 3, 10, 5, 16, 8, 4, 2, 1.

Since <TT>n</TT> sometimes increases and sometimes decreases, there is no obvious proof that <TT>n</TT> will ever reach 1, or that the program terminates. For some particular values of <TT>n</TT>, we can prove termination. For example, if the starting value is a power of two, then the value of <TT>n</TT> will be even each time through the loop until it reaches 1. The previous example ends with such a sequence, starting with 16.

The hard question is whether we can prove that this program terminates for all positive values of <TT>n</TT>. So far<SUP>1</SUP>, no one has been able to prove it or disprove it!

<DIV CLASS="theorem">Exercise&#XA0;1&#XA0;&#XA0; Rewrite the function   from Section&#XA0;'5.8' using iteration instead of recursion. </DIV>

<TT>break</TT>
Sometimes you don&#X2019;t know it&#X2019;s time to end a loop until you get half way through the body. In that case you can use the <TT>break</TT> statement to jump out of the loop.

For example, suppose you want to take input from the user until they type <TT>done</TT>. You could write: The loop condition is <TT>True</TT>, which is always true, so the loop runs until it hits the break statement.

Each time through, it prompts the user with an angle bracket. If the user types <TT>done</TT>, the <TT>break</TT> statement exits the loop. Otherwise the program echoes whatever the user types and goes back to the top of the loop. Here&#X2019;s a sample run: This way of writing <TT>while</TT> 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 (&#X201C;stop when this happens&#X201D;) rather than negatively (&#X201C;keep going until that happens.&#X201D;).

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&#X2019;s method. Suppose that you want to know the square root of <I>a</I>. If you start with almost any estimate, <I>x</I>, you can compute a better estimate with the following formula: </TD><TD CLASS="dcell">&#XA0;</TD></TR> </TABLE>

For example, if <I>a</I> is 4 and <I>x</I> is 3: Which is closer to the correct answer (&#X221A;<SPAN style="text-decoration:overline">4</SPAN> = 2). If we repeat the process with the new estimate, it gets even closer: After a few more updates, the estimate is almost exact:

In general we don&#X2019;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: When <TT>y == x</TT>, we can stop. Here is a loop that starts with an initial estimate, <TT>x</TT>, and improves it until it stops changing: For most values of <TT>a</TT> this works fine, but in general it is dangerous to test <TT>float</TT> equality. Floating-point values are only approximately right: most rational numbers, like 1/3, and irrational numbers, like &#X221A;<SPAN style="text-decoration:overline">2</SPAN>, can&#X2019;t be represented exactly with a <TT>float</TT>.

Rather than checking whether <TT>x</TT> and <TT>y</TT> are exactly equal, it is safer to use the built-in function <TT>abs</TT> to compute the absolute value, or magnitude, of the difference between them: Where  has a value like <TT>0.0000001</TT> that determines how close is close enough.

<DIV CLASS="theorem">Exercise&#XA0;2&#XA0;&#XA0;

Encapsulate this loop in a function called   that takes '<TT>a</TT>' as a parameter, chooses a reasonable value of '<TT>x</TT>', and returns an estimate of the square root of '<TT>a</TT>'. </DIV>

Algorithms
Newton&#X2019;s method is an example of an algorithm: it is a mechanical process for solving a category of problems (in this case, computing square roots).

It is not easy to define an algorithm. It might help to start with something that is not an algorithm. When you learned to multiply single-digit numbers, you probably memorized the multiplication table. In effect, you memorized 100 specific solutions. That kind of knowledge is not algorithmic.

But if you were &#X201C;lazy,&#X201D; you probably cheated by learning a few tricks. For example, to find the product of <I>n</I> and 9, you can write <I>n</I>&#X2212;1 as the first digit and 10&#X2212;<I>n</I> as the second digit. This trick is a general solution for multiplying any single-digit number by 9. That&#X2019;s an algorithm!

Similarly, the techniques you learned for addition with carrying, subtraction with borrowing, and long division are all algorithms. One of the characteristics of algorithms is that they do not require any intelligence to carry out. They are mechanical processes in which each step follows from the last according to a simple set of rules.

In my opinion, it is embarrassing that humans spend so much time in school learning to execute algorithms that, quite literally, require no intelligence.

On the other hand, the process of designing algorithms is interesting, intellectually challenging, and a central part of what we call programming.

Some of the things that people do naturally, without difficulty or conscious thought, are the hardest to express algorithmically. Understanding natural language is a good example. We all do it, but so far no one has been able to explain how we do it, at least not in the form of an algorithm.

Debugging
As you start writing bigger programs, you might find yourself spending more time debugging. More code means more chances to make an error and more place for bugs to hide.

One way to cut your debugging time is &#X201C;debugging by bisection.&#X201D; For example, if there are 100 lines in your program and you check them one at a time, it would take 100 steps.

Instead, try to break the problem in half. Look at the middle of the program, or near it, for an intermediate value you can check. Add a <TT>print</TT> statement (or something else that has a verifiable effect) and run the program.

If the mid-point check is incorrect, the problem must be in the first half of the program. If it is correct, the problem is in the second half.

Every time you perform a check like this, you halve the number of lines you have to search. After six steps (which is much less than 100), you would be down to one or two lines of code, at least in theory.

In practice it is not always clear what the &#X201C;middle of the program&#X201D; is and not always possible to check it. It doesn&#X2019;t make sense to count lines and find the exact midpoint. Instead, think about places in the program where there might be errors and places where it is easy to put a check. Then choose a spot where you think the chances are about the same that the bug is before or after the check.

Glossary
<DL CLASS="description"><DT CLASS="dt-description">multiple assignment:</DT><DD CLASS="dd-description"> Making more than one assignment to the same variable during the execution of a program.

</DD><DT CLASS="dt-description">update:</DT><DD CLASS="dd-description"> An assignment where the new value of the variable depends on the old. </DD><DT CLASS="dt-description">initialize:</DT><DD CLASS="dd-description"> An assignment that gives an initial value to a variable that will be updated.</DD><DT CLASS="dt-description">increment:</DT><DD CLASS="dd-description"> An update that increases the value of a variable (often by one). </DD><DT CLASS="dt-description">decrement:</DT><DD CLASS="dd-description"> An update that decreases the value of a variable. </DD><DT CLASS="dt-description">iteration:</DT><DD CLASS="dd-description"> Repeated execution of a set of statements using either a recursive function call or a loop. </DD><DT CLASS="dt-description">infinite loop:</DT><DD CLASS="dd-description"> A loop in which the terminating condition is never satisfied. </DD></DL>

Exercise 3
''To test the square root algorithm in this chapter, you could compare it with '<TT>math.sqrt</TT>'. Write a function named   that prints a table like this:''

The first column is a number, '<I>a</I>'; the second column is the square root of '<I>a</I>' computed with the function from Exercise&#XA0;'7.2'; the third column is the square root computed by '<TT>math.sqrt</TT>'; the fourth column is the absolute value of the difference between the two estimates.

Exercise 4
''The built-in function '<TT>eval</TT>' takes a string and evaluates it using the Python interpreter. For example:'' Write a function called   that iteratively prompts the user, takes the resulting input and evaluates it using '<TT>eval</TT>', and prints the result.

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

Exercise 5
The brilliant mathematician Srinivasa Ramanujan found an infinite series<SUP>2</SUP> that can be used to generate a numerical approximation of $$\pi$$:

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

Write a function called  '' that uses this formula to compute and return an estimate of '&#X3C0;'. It should use a '<TT>while</TT>' loop to compute terms of the summation until the last term is smaller than '<TT>1e-15</TT>' (which is Python notation for 10<SUP>&#X2212;15</SUP>). You can check the result by comparing it to '<TT>math.pi</TT>'.''

You can see my solution at '<TT>thinkpython.com/code/pi.py</TT>'.

<HR CLASS="footnoterule"> <DL CLASS="thefootnotes"> <DT CLASS="dt-thefootnotes">1</DT><DD CLASS="dd-thefootnotes">See <TT>wikipedia.org/wiki/Collatz_conjecture</TT>.</DD> <DT CLASS="dt-thefootnotes">2</DT><DD CLASS="dd-thefootnotes">See <TT>wikipedia.org/wiki/Pi</TT>.</DD> </DL>