SENTINEL-CONTROLLED ITERATION
Develop a classaveraging program that processes an arbitrary number of grades each time the program executes.
The requirements statement does not state what the grades are or how many there are, so we’re going to have the user enter the grades. The program processes an arbitrary number of grades. The user enters grades one at a time until all the grades have been entered, then enters a sentinel value (also called a signal value, a dummy value or a flag value) to indicate that there are no more grades.
Implementing Sentinel-Controlled Iteration
The following script solves the class average problem with sentinelcontrolled iteration. Notice that we test for the possibility of division by zero. If undetected, this would cause a fatal logic error. In the “Files and Exceptions” chapter, we write programs that recognize such exceptions and take appropriate actions.
2 """Class average program with sentinelcontrolled iteration."""
3
4 # initialization phase
5 total = 0 # sum of grades
6 grade_counter = 0 # number of grades entered
7
8 # processing phase
9 grade = int(input('Enter grade, 1 to end: ')) # get one grade
10
11 while grade != -1:
12 total += grade
13 grade_counter += 1
14 grade = int(input('Enter grade, 1 to end: '))
15
16 # termination phase
17 if grade_counter != 0:
18 average = total / grade_counter
19 print(f'Class average is {average:.2f}')
20 else:
Enter grade, 1 to end: 97
Enter grade, 1 to end: 88
Enter grade, 1 to end: 72
Enter grade, 1 to end: 1
Class average is 85.67
Program Logic for Sentinel-Controlled Iteration
Next, line 14 inputs another grade from the user and the condition (line 11) is tested again, using the most recent grade entered by the user. The value of grade is always input immediately before the program tests the while condition, so we can determine whether the value just input is the sentinel before processing that value as a grade.
Formatting the Class Average with Two Decimal Places
This example formatted the class average with two digits to the right of the decimal point. In an fstring, you can optionally follow a replacementtext expression with a colon (:) and a format specifier that describes how to format the replacement text. The format specifier .2f (line 19) formats the average as a floating-point number (f) with two digits to the right of the decimal point (.2). In this example, the sum of the grades was 257, which, when divided by 3, yields 85.666666666.... Formatting the average with .2f rounds it to the hundredths position, producing the replacement text 85.67. An average with only one digit to the right of the decimal point would be formatted with a trailing zero (e.g., 85.50). The chapter “Strings: A Deeper Look” discusses many more stringformatting features.