Looping When We Don’t Know When We’ll Stop

While loops are typically used when you don’t know how many times the loop needs to repeat. The body of the loop will repeat while the condition is true. The logical expression will be evaluated just before the body of the loop is repeated.

Let’s say that we want to find the square root of a number. For some square roots, you’re never going to be exact. Let’s say that we want to find a square root that, when multiplied by itself, is within 0.01 of the square we want. How do we do it? There’s a really old process that we can apply here.

  1. Start by guessing 2.

  2. Compute the guess squared.

  3. Is the guess squared close to the target number? If it’s within 0.01, we’re done. We’ll take the absolute value of the difference, in case we overshoot. (In Python, abs is the absolute value function.)

  4. If it’s not close enough, we divide the target number by our guess, then average that value with our guess.

  5. That’s our new guess. Square it, and go back to Step #3.

Here’s a program that does exactly that. Try different target values, and see how good it is at computing square roots.

Let’s say that you wanted to figure out the square root of 6. How many times would the body of the while loop be executed? We could figure it out by tracing the program.

How about the square root of 25? How about 2,356? It’s difficult to know ahead of time how many times the loop will execute. That’s where the while loop really shines, when you can specify an end condition (or rather, a continue condition).


Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page