Example 8: The use of a sentinel value in while loops « PD4CS (2024)

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.pyscore = input("enter a test score, use -1 to stop ") #enter the first valuetotal = 0scoreCounter = 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).

This entry was posted in Loops – Python. Bookmark the permalink.

Example 8: The use of a sentinel value in while loops « PD4CS (2024)
Top Articles
Latest Posts
Article information

Author: Edwin Metz

Last Updated:

Views: 6082

Rating: 4.8 / 5 (78 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.