When using this repetition statement, the condition is tested at the top or beginning of the loop. If, upon that initial test, the condition is true, then the body of the loop is executed; otherwise, it is not, and the statement following the loop is executed. This means that it is possible that the code in the loop is not executed at all. The condition tested is the same kind of expression that is evaluated in an if statement: one that evaluates to True or False. It could be, and often is, a comparison between two numeric or string values, as it is in the example of Figure 2.1.
When the code in the body of the while statement has been executed, then the condition is tested again. If it is still true, then the body of the loop is executed again, otherwise the loop is exited and the statement following the loop is executed. There is an implication in this description that the body of the loop must change something that is used in the evaluation of the loop condition, otherwise the condition will always be the same and the loop will never terminate. Here is an example of a loop that is entered and terminates:
a = 0
b = 0
while a < 10:
a = a + 1
print (a)
The condition a<10 is true at the outset because a has the value 0, so the code in the loop is executed. The lone statement in this loop increments a, so that after the first time the loop is executed the value of a is 1. Now the condition is tested and, again, a<10, so the loop executes again. In the final iteration of the loop, the value of a starts out as 9, is incremented, and becomes 10. When the condition is tested it fails, because a is no longer less than 10 (it is equal) and so the loop ends. The statement following the loop is print (a) and the value printed is 10. This loop explicitly modifies one of the variables in the loop condition, and it is easy to see that the loop will end and what the value of a will be at that time.
Here is an example of a loop that is entered and does not terminate:
a = 0
b = 0
while b < 10:
a = a + 1
print (a)
In this case, the value of b is less than 10 at the outset, so the loop is entered. The body of the loop increments a as before, but does not change b. The loop condition does not depend on a, only on b, so when the loop condition is tested again, the value of b is still 0, and the loop executes again. The value of b will always be 0 each time it is tested, so the loop condition will always be true and the loop will never end. The print statement will never be executed.
When this program is executed, the computer will seem to become unresponsive. As long as the loop is executing the program can do nothing else, and so the only indication that something is wrong is that nothing is happening. There are many reasons why a program can appear to be doing nothing: when waiting for the user to type some input, for instance, or when performing an especially difficult calculation. However, in this case, which is called an infinite loop, the only thing to do is to terminate the program and fix the loop.
Here is an example of a loop that is not entered:
a = 100
b = 0
while a < 10:
a = a + 1
print (a)
The condition a<10 is false at the outset because a has the value 100, so the code in the loop is not executed. The statement following the loop is executed next, which is the print statement, and the value printed is 100.
These loops are examples that illustrate the three possibilities for a while loop and do not calculate anything useful. The two examples from the previous chapter can make practical use of a while loop, and it would be useful to look at those again.
1. The Guess-A-Number Program Revisited
The program as it was written in Chapter 1 is as follows:
choice = 7
print (“Please guess a number between 1 and 10:”)
playerchoice = int(input()) if choice == playerchoice:
print (“You win!”)
else:
print (“Sorry, You lose.”)
The game would be better if it allowed the player to guess again, perhaps until a correct guess was achieved. A while loop could be used to accomplish this. Think about what the condition might be. The loop should end when the player guesses the answer. Another way to say this is that the loop should continue so long as the player has not guessed the answer. The condition is one for continuation of the loop, not termination, so the loop must be constructed in such a way that it continues when the condition is true. The loop will begin with this:
while choice != playerchoice:
At the beginning of the loop, the variables choice and playerchoice must be defined. This means that before the while statement there must be code that does this. The program now looks like this:
choice = 7
print (“Please guess a number between 1 and 10: “)
playerchoice = int(input())
while choice != playerchoice:
If the player has guessed incorrectly, then the body of the loop will execute. What should be done? One of the variables in the condition has to be changed, and the goal of the program must be kept in mind. In this case, because the player has guessed incorrectly, two things should happen. First, the player must be told that they are wrong and to make another guess. Next, the new guess must be read into the variable playerchoice, thus satisfying the rule that the loop condition must possibly have an opportunity to become False. The program is now
choice = 7
print (“Please guess a number between 1 and 10: “)
playerchoice = int(input()) while choice != playerchoice:
print (“Sorry, not correct. Guess again: “)
playerchoice = int(input())
When the player finally guesses the number, the loop will exit; if the first guess is correct, then the condition fails at the beginning, and this amounts to the same thing in this case. The last thing to do is to print a message to the player:
choice = 7
print (“Please guess a number between 1 and 10: “)
playerchoice = int(input()) while choice != playerchoice:
print (“Sorry, not correct. Guess again: “)
playerchoice = int(input())
print (“You have guessed correctly.”)
Note that, as was true with the if statement and as is always true in Python, the indentation indicates which statements are a part of the loop (the suite) and which are outside.
2. Modifying the Game
A simple modification of the game involves telling the player whether their guess was too large or too small. This will help them shrink the possible range of values and thus guess the right answer more quickly. A modification to the body of the loop will accomplish this. If the value that the player guessed is smaller than the target, then a message to that effect is printed, and similarly if the player guesses a value larger than the target. The use of an if statement here is appropriate, and that if statement is nested inside of the while loop:
choice = 7
print (“Please guess a number between 1 and 10: “)
playerchoice = int(input()) while choice != playerchoice:
if (playerchoice < choice):
print (“Sorry, your guess was too small.Guess again: “)
else:
print (“Sorry, your guess was too large.Guess again.”)
playerchoice = int(input())
print (“You have guessed correctly.”)
This program illustrates a second level of indentation. The if-else are indented to indicate they are part of the while statement. The print statements are indented further, to show that they are also part of the if statement.
Doing some printing inside of the loop is useful because an infinite loop will be obvious. It will print many lines and never stop. It’s not always practical to do that, so a degree of careful analysis should always be done to ensure that the loop can and will terminate.
Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.