• No results found

initializes the variable gradeCounter to 0, because no grades have been entered To keep an accurate record of the number of grades entered, variable grade-

In document Python - How to Program (Page 89-93)

Refinement: Case Study 2 (Sentinel-Controlled Repetition) Let us generalize the class-average problem Consider the following problem:

Line 6 initializes the variable gradeCounter to 0, because no grades have been entered To keep an accurate record of the number of grades entered, variable grade-

Counter is incremented only when a grade value is entered.

Good Programming Practice 3.5

In a sentinel-controlled loop, the prompts requesting data entry should explicitly remind the

user of the sentinel value. 3.5

Study the difference between the program logic for sentinel-controlled repetition in Fig. 3.13 and counter-controlled repetition in Fig. 3.10. In counter-controlled repetition, the program reads a value from the user during each pass of the while structure, for a specified number of passes. In sentinel-controlled repetition, the program reads one value (lines 9–10) before the program reaches the while structure. This value determines whether the program’s flow of control should enter the body of the while structure. If the

while structure condition is false (i.e., the user has already typed the sentinel), the pro- gram does not execute the while loop (no grades were entered). On the other hand, if the condition is true, the program executes the while loop and processes the value entered by the user (i.e., adds the grade to total). After processing the grade, the program requests the user to enter another grade. After executing the last (indented) line of the

while loop (line 16), execution continues with the next test of the while structure con- dition, using the new value just entered by the user to determine whether the while struc- ture’s body should execute again. Notice that the program requests the next value before evaluating the while structure. This allows for determining whether the value just entered by the user is the sentinel value before processing the value (i.e., adding it to total). If the value entered is the sentinel value, the while structure terminates, and the value is not added to total.

Lines 9–10 and 15–16 contain identical lines of code. In Section 3.15, we introduce programming constructs that help the programmer avoid repeating code.

Averages do not always evaluate to integer values. Often, an average is a value that contains a fractional part, such as 7.2 or –93.5. These values are referred to as floating-point numbers.

The calculation total / gradeCounter results in an integer, because total and

counter contain integer values. Dividing two integers results in integer division, in which any fractional part of the calculation is discarded (i.e., truncated). The calculation is per- formed first, the fractional part is discarded before assigning the result to average. To produce a floating-point calculation with integer values, convert one (or both) of the values to a floating-point value with function float. Recall that functions are pieces of code that accomplish a task; in line 20, functionfloatconverts the integer value of variable sum to a floating-point value. The calculation now consists of a floating-point value divided by the integer gradeCounter.

The Python interpreter knows how to evaluate expressions in which the data types of the operands are identical. To ensure that the operands are of the same type, the interpreter

performs an operation called promotion (also called implicit conversion) on selected oper- ands. For example, in an expression containing integer and floating-point data, integer operands are promoted to floating point. In our example, the value of gradeCounter is promoted to a floating-point number. Then, the calculation is performed, and the result of the floating-point division is assigned to variable average.

Common Programming Error 3.9

Assuming that all floating-point numbers are precise can lead to incorrect results. Most com-

puters approximate floating-point numbers. 3.9

Despite the fact that floating-point numbers are not precise, they have numerous appli- cations. For example, when we speak of a “normal” body temperature of 98.6, we do not need to be precise to a large number of digits. When we view the temperature on a ther- mometer and read it as 98.6, it may actually be 98.5999473210643. The point here is that calling this number simply 98.6 is adequate for most applications.

Another way floating-point numbers develop is through division. When we divide 10 by 3, the result is 3.3333333…, with the sequence of 3s repeating infinitely. The computer allocates a fixed amount of space to hold such a value, so the stored floating-point value only can be an approximation.

3.10 Formulating Algorithms with Top-Down, Stepwise

Refinement: Case Study 3 (Nested Control Structures)

Let us work another complete problem. We once again formulate the algorithm using pseudocode and top-down, stepwise refinement and we develop a corresponding Python program. Consider the following problem statement:

A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, several of the students who completed this course took the licensing examination. Naturally, the college wants to know how well its students did on the exam. You have been asked to write a program to summarize the results. You have been given a list of these 10 students. Next to each name is written a 1 if the student passed the exam and a 2 if the student failed.

Your program should analyze the results of the exam as follows:

1. Input each test result (i.e., a 1 or a 2). Display the message “Enter result” on the screen each time the program requests another test result.

2. Count the number of test results of each type.

3. Display a summary of the test results indicating the number of students who passed and the number of students who failed.

4. If more than 8 students passed the exam, print the message “Raise tuition.”

After reading the problem statement carefully, we make the following observations about the problem:

1. The program must process 10 test results. A counter-controlled loop will be used. 2. Each test result is a number—either a 1 or a 2. Each time the program reads a test result, the program must determine if the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it is a 2. (An exercise at the end of the chapter considers the consequences of this assumption.)

3. Two counters are used—one to count the number of students who passed the exam and one to count the number of students who failed the exam.

4. After the program has processed all the results, it must decide if more than eight students passed the exam.

Let us proceed with top-down, stepwise refinement. We begin with a pseudocode rep- resentation of the top:

Analyze exam results and decide if tuition should be raised

Once again, it is important to emphasize that the top is a complete representation of the pro- gram, but several refinements are likely to be needed before the pseudocode can evolve nat- urally into a Python program. Our first refinement is

Initialize variables

Input the ten exam grades and count passes and failures

Print a summary of the exam results and decide if tuition should be raised

Here, too, even though we have a complete representation of the entire program, further re- finement is necessary. We now commit to specific variables. We need counters to record the passes and failures, a counter to control the looping process and a variable to store the user input. The pseudocode statement

Initialize variables can be refined as follows:

Initialize passes to zero Initialize failures to zero Initialize student counter to one

Notice that only the counters for the number of passes, number of failures and number of students are initialized. The pseudocode statement

Input the ten exam grades and count passes and failures

requires a loop that successively inputs the result of each exam. Here it is known in advance that there are precisely ten exam results, so counter-controlled looping is appropriate. In- side the loop (i.e., nested within the loop), a double-selection structure determines whether each exam result is a pass or a failure and increments the appropriate counter accordingly. The refinement of the preceding pseudocode statement is

While student counter is less than or equal to ten Input the next exam result

If the student passed Add one to passes else

Add one to failures Add one to student counter

Notice the use of blank lines to set off the If/else control structure to improve program read- ability. The pseudocode statement

may be refined as follows: Print the number of passes Print the number of failures If more than eight students passed

Print “Raise tuition”

The complete second refinement appears in Fig. 3.14. Notice that the pseudocode also uses blank lines to set off the while structure for program readability.

This pseudocode is now sufficiently refined for conversion to Python. Figure 3.15 shows the Python program and two sample executions.

Initialize passes to zero Initialize failures to zero Initialize student counter to one

While student counter is less than or equal to ten Input the next exam result

If the student passed Add one to passes else

Add one to failures Add one to student counter Print the number of passes Print the number of failures If more than eight students passed

Print “Raise tuition”

Fig. 3.14 Fig. 3.14 Fig. 3.14

Fig. 3.14 Pseudocode for examination-results problem.

1 # Fig. 3.15: fig03_15.py

2 # Analysis of examination results. 3

4 # initialize variables

5 passes = 0 # number of passes 6 failures = 0 # number of failures 7 studentCounter = 1 # student counter 8

9 # process 10 students; counter-controlled loop 10 while studentCounter <= 10:

11 result = raw_input( "Enter result (1=pass,2=fail): " ) 12 result = int( result ) # one exam result

Fig. 3.15 Fig. 3.15 Fig. 3.15

Note that line 14 uses the equality operator (==) to test whether the value of variable

result equals 1. Be careful not to confuse the equality operator with the assignment symbol (=). Such confusion can cause syntax or logic errors in Python.

Common Programming Error 3.10

Using the = symbol for equality in a conditional statement is a syntax error. 3.10 13 14 if result == 1: 15 passes = passes + 1 16 else: 17 failures = failures + 1 18 19 studentCounter = studentCounter + 1 20 21 # termination phase 22 print "Passed", passes 23 print "Failed", failures 24

25 if passes > 8:

26 print "Raise tuition"

Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 2 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Passed 9

Failed 1

In document Python - How to Program (Page 89-93)