A sentinel value is a special value used to terminate a loop when reading data. In the following program, test scores are provided (via user input). Once the sentinel value of -1 is input, the loop terminates. At that point, the average of the test scores will be printed.
# 02Loops example_08 SentinalValue.py
score = input("enter a test score, use -1 to stop ") #enter the first value
total = 0
scoreCounter = 0
while score != -1: #loop until the sentinel value (-1) is entered
total = total + score
scoreCounter = scoreCounter + 1
score = input("enter a test score, use -1 to stop ")
print ("The average for the test is ",total/scoreCounter)
This problem can be extended in a number of ways.
- Ask students to maintain the minimum and maximum score in the while loop.
- Ask students to store the values input in a list which can then be sorted and analyzed (e.g., determine the median score, 25% percentile, the score that appears most often).
