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