A simple adding machine.
Watch this video to learn about the new concepts shown in the program:
A “sentinel” is a dummy value that is used to terminate a while iteration. Most commonly used with the input command to mark the end of an input stream.
You have to be careful that the sentinel value is not valid data.
You can use True as a value to create an infinite loop. E.g. while True: will never end because True is always True. This can be useful if you don’t want your program to end unless the user closes the program.
Questions to think about with this program to check your understanding:
Explain why line 13:
number = float(input("Enter number: "))
must be after line 12:
while not complete:
and not before.
You want the user to be able to keep entering numbers until they enter zero, so the input must be inside the loop.
What is the problem with using zero as the sentinel value in line 14?
It means that zero can never be input as a valid number. This is a problem if you want the data set to include zeros for the purpose of calculating the average. A better approach would be to input a number as a string and cast it to an integer after checking if the value is an empty string first. The empty string then becomes the sentinel value and not the number zero.
Change the program so that it:
Hint
The lowest number will need to be initialised to be the first number that is input.
Enter number: 4
Enter number: 2
Enter number: 8
Enter number: 6
Enter number: e
Total: 20.0 Top: 8.0 Bottom: 2.0 Ave: 5.0
# Adder program
# -------------------------
# Subprograms
# -------------------------
# A simple adding machine
def adder():
---
# Initialise variables
total = 0 # Total
top = 0 # Highest number
bottom = 0 # Lowest number
count = 0 # Count of numbers
ave = 0 # Average
complete = False
---
# Repeat until sentinel value entered 'e'
while not complete:
---
data = input("Enter number: ")
---
# Add the number if it is not the sentinel
if data != "e":
---
number = float(data)
total = total + number
count = count + 1
---
# Set the highest number
---
if number > top:
---
top = number
---
# Set the lowest number
---
if count == 1 or number < bottom:
---
bottom = number
---
else:
---
complete = True
---
# Prevent a division by zero error
if count > 0:
---
ave = total / count
---
else:
---
ave = 0
---
print("Total:", total, "Top:", top, "Bottom:", bottom, "Ave:", ave)
---
# -------------------------
# Main program
# -------------------------
adder()