Subsection 8.8.1 Sentinel Values
Indefinite loops are much more common in the real world than definite loops.
If you are selling tickets to an event, you don’t know in advance how many tickets you will sell. You keep selling tickets as long as people come to the door and there’s room in the hall.
When the baggage crew unloads a plane, they don’t know in advance how many suitcases there are. They just keep unloading while there are bags left in the cargo hold. (Why your suitcase is always the last one is an entirely different problem.)
When you go through the checkout line at the grocery, the clerks don’t know in advance how many items there are. They just keep ringing up items as long as there are more on the conveyor belt.
Let’s implement the last of these in Python, by asking the user for prices and keeping a running total and count of items. When the last item is entered, the program gives the grand total, number of items, and average price. We’ll need these variables:
total - this will start at zero
count - the number of items, which also starts at zero
moreItems - a boolean that tells us whether more items are waiting; this starts as True
The pseudocode (code written half in English, half in Python) for the body of the loop looks something like this:
ask for price
add price to total
add one to count
This pseudocode has no option to set
False, so it would run forever. In a grocery store, there’s a little plastic bar that you put after your last item to separate your groceries from those of the person behind you; that’s how the clerk knows you have no more items. We don’t have a “little plastic bar” data type in Python, so we’ll do the next best thing: we will use a
price of zero to mean “this is my last item.” In this program, zero is a sentinel value, a value used to signal the end of the loop. Here’s the code:
There are still a few problems with this program.
If you enter a negative number, it will be added to the total and count. Modify the code so that negative numbers give an error message instead (but don’t end the loop) Hint:
elif is your friend.
If you enter zero the first time you are asked for a price, the loop will end, and the program will try to divide by zero. Use an
else statement outside the loop to avoid the division by zero and tell the user that you can’t compute an average without data.
This program doesn’t display the amounts to two decimal places. In the next chapter you will see the Section 9.5
that will do the trick.
Check your understanding
True or False: A while loop will continue to iterate forever unless it meets a condition to stop.
Keep in mind there are multiple ways to stop a while loop, such as a sentinal value.
While loops do not have a set number of times they will iterate, so they will continue until something breaks the loop. Keep this in mind while coding with while loops.