8.4. Other uses of while

Sentinel Values

Indefinite loops are much more common in the real world than definite loops.

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:

The pseudocode (code written half in English, half in Python) for the body of the loop looks something like this:

while more_items
    ask for price
    add price to total
    add one to count

This pseudocode has no option to set more_items to 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:

 
1
total: float
2
count: int
3
more_items: bool
4
price: float
5
average: float
6
7
total = 0.0
8
count = 0
9
more_items = True
10
while more_items:
11
    print('Enter price of item (0 when done): ')
12
    price = float(input())
13
    if price != 0.0:
14
        count = count + 1
15
        total = total + price
16
        print('Subtotal: $' + str(total))
17
    else:
18
        more_items = False
19
average = total / float(count)
20
print('Total items: ' + str(count))
21
print('Total $' + str(total))
22
print('Average price per item: $' + str(average))
23

(ch07_sentinel)

There are still a few problems with this program.

Validating Input

You can also use a while loop when you want to validate input; when you want to make sure the user has entered valid input for a prompt. Let’s say you want a function that asks a yes-or-no question. In this case, you want to make sure that the person using your program enters either a Y for yes or N for no (in either upper or lower case). Here is a program that uses a while loop to keep asking until it receives a valid answer. When you run the following code, try typing something other than Y or N to see how the code reacts:

24
 
1
def get_yes_or_no(message: str) -> str:
2
    valid_input: bool
3
    answer: str
4
    valid_input = False
5
    while not valid_input:
6
        print(message)
7
        answer = input()
8
        if answer == 'Y' or answer == 'N':
9
            valid_input = True
10
        else:
11
            print('Please enter Y for yes or N for no.')
12
    return answer
13
14
def main() -> None:
15
    response: str
16
    response = get_yes_or_no('Do you like lima beans? Y)es or N)o: ')
17
    if response == 'Y':
18
        print('Great! They are very healthy.')
19
    else:
20
        print('Too bad. If cooked right, they are quite tasty.')
21
    return None
22
23
main()
24

(ch07_validation)

You have attempted 1 of 3 activities on this page
Next Section - 8.5. Glossary