Lesson 3: Iteration
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. In a computer program, repetition is also called iteration.
Because iteration is so common, Python provides language features to make it easier.
The while Statement
The while statement allows you to repeatedly execute a block of
statements so long as a condition is true. It is considered to be a
condition-controlled statement.
The simplest form of the while statement is this:
while
[condition]:
[do something]
Just like with the if statement, the Boolean expression after
while is called the condition. If the condition is
true, the body of the while statement executes. Once the body
is completed, the condition is re-evaluated. If it is found to still be
true, then the body executes again. This repeats until the condition is
found to be false. At that point, the while statement stops
and the rest of the program continues to run.
More formally, here is the flow of execution for a while
statement:
- Determine whether the condition is true or false.
- If false, exit the
whilestatement and continue execution at the next statement. - If the condition is true, run 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.
Pretest Loop
The while statement is considered to be a pretest loop – this
means it tests the condition before it decided to execute. So if you need
to run the body of the while statement at least once, you may need
to prime the while statement by setting the condition to be true
ahead of time.
Example: Bad Joke
Here is a program which tells a knock knock joke using a while
statement:
knock_knock = True
while
knock_knock:
print("\nKnock,
knock!")
print(" Who's
there?")
print("Banana.")
print("
Banana who?\n")
again =
input("Continue the joke? y/n
")
if
again!="y":
knock_knock
= False
print("\nKnock, knock!")
print(" Who's
there?")
print("Orange.")
print(" Orange who?")
print("Orange you
glad I didn't say 'banana'?")
Output
Knock, knock!
Who's
there?
Banana.
Banana who?
Continue the joke? y/n
y
Knock, knock!
Who's
there?
Banana.
Banana who?
Continue the joke? y/n
n
Knock, knock!
Who's
there?
Orange.
Orange who?
Orange you glad I didn't say
'banana'?
How it Works
We've set a condition control knock_knock equal to True.
The while statement checks that knock_knock is true, then performs
the actions in the body of the statement. In this case, the user is
prompted to enter a value, the value is evaluated using a conditional
statement.
| Code | Output | Explanation |
|---|---|---|
knock_knock = True |
None |
First, we assign the Boolean value |
while knock_knock: |
None |
We begin the |
print("\nKnock, knock!") |
Knock, knock! |
We display the beginning of a bad knock knock joke. |
again = input("Continue the joke? y/n
") |
Continue the joke? y/n |
We accept input from the user. |
if again!="y": |
None |
We evaluate the input. If the user enters something other than
'y' we set the value of |
print("\nKnock, knock!") |
Knock, knock! |
After we set the value of |
Example: Countdown
Here is a program which counts down to 0 using a while
statement:
n = 5
while n >
0:
print(n)
n = n –
1
print('Blastoff!')
Output
5
4
3
2
1
Blastoff!
How it Works
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!"
| Code | Output | Explanation |
|---|---|---|
n = 5 |
None |
First, we assign the literal constant value |
while n > 0: |
None |
We begin the |
print(n) n = n – 1 |
5 |
We display the value of |
while n > 0: |
None |
We re-evaluate the condition again. |
print(n) n = n – 1 |
4 |
We display the value of |
while n > 0: |
None |
We re-evaluate the condition again. |
print(n) n = n – 1 |
3 |
We display the value of |
while n > 0: |
None |
We re-evaluate the condition again. |
print(n) n = n – 1 |
2 |
We display the value of |
while n > 0: |
None |
We re-evaluate the condition again. |
print(n) n = n – 1 |
1 |
We display the value of |
while n > 0: |
None |
We re-evaluate the condition again. |
print('Blastoff!') |
Blastoff! |
We display the word Blastoff! The program is finished. |
Infinite Loops
The body of the loop should change the value of one or more variables so that the condition becomes false eventually 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, "Lather, rinse, repeat", are an infinite loop.
In the case of the countdown, we can prove that the loop terminates: if
n is zero or negative, the loop never runs. Otherwise,
n gets smaller by one each time through the loop, so eventually we
have to get to 0.
For some other loops, it is not so easy to tell. For example:
while
n !=
1:
print(n)
if
n % 2 == 0:
# n is
even
n = n /
2
else:
# n
is odd
n = n*3 + 1
The condition for this loop is n != 1, so the loop will continue
until n is 1, which makes the condition false.
Each time through the loop, the program outputs the value of n
and then checks whether it is even or odd. If it is even, n is
divided by 2. If it is odd, the value of n is replaced with
n*3 + 1. For example, if the argument passed to sequence is 3, the
resulting values of n are 3, 10, 5, 16, 8, 4, 2, 1.
Since n sometimes increases and sometimes decreases, there is no
obvious proof that n will ever reach 1, or that the program
terminates. For some particular values of n, we can prove
termination. For example, if the starting value is a power of two,
n will be even every 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 n. So far, no one has been able to prove it
or disprove it! (See http://en.wikipedia.org/wiki/Collatz_conjecture
.)
else: Alternative Execution
A while statement can have an optional else
clause. This code will execute once the condition is no longer true.
We can re-write the Countdown program using the else clause like
this:
n = 5
while n >
0:
print(n)
n = n –
1
else:
print('Blastoff!')
We will get the exact same output.
Example: Number Guessing, Part 2
In this program, we are still playing the guessing game, but the advantage is
that the user is allowed to keep guessing until he guesses correctly - there is
no need to repeatedly run the program for each guess, as we have done in the
previous section. This aptly demonstrates the use of the while
statement.
number = 23
running = True
while
running:
guess = int(input('Enter an integer:
'))
if guess ==
number:
print('You guessed
it!')
running =
False
elif guess <
number:
print('No, you are
too low!')
else:
print('No, you are too
high!')
else:
print('The while loop is
over.')
print('Done')
Output:
Enter an integer: 50
No, you are too
high!
Enter an integer: 22
No, you are too
low!
Enter an integer: 23
You guessed it!
The
while loop is over.
Done
How It Works
| Code | Output | Explanation |
|---|---|---|
number = 23 |
None |
First, we assign the literal constant value |
while running: |
Varies depending on the user’s input |
We move the First, we check if the variable After this block is executed, the condition is again checked which in
this case is the If it is true, we execute the while-block again, otherwise we continue to execute the optional else-block and then continue to the next statement. Notice that when the correct number is guessed, we change the value of
|
else: |
The while loop is over. |
The |
print('Done') |
Done |
The |
