3.10 Program Development: Sequence-Controlled Repetition

Experience has shown that the most challenging part of solving a problem on a computer is developing an algorithm for the solution. As you’ll see, once a correct algorithm has been specified, creating a working Python program from the algorithm is typically straightforward. This section and the next present problem solving and program development by creating scripts that solve two class-averaging problems.

3.10.1 Requirements Statement

A requirements statement describes what a program is supposed to do, but not how the program should do it. Consider the following simple requirements statement:

  • A class of ten students took a quiz. Their grades (integers in the range 0 – 100) are 98, 76, 71, 87, 83, 90, 57, 79, 82, 94. Determine the class average on the quiz.

Once you know the problem’s requirements, you can begin creating an algorithm to solve it. Then, you can implement that solution as a program.

The algorithm for solving this problem must:

  1. Keep a running total of the grades.

  2. Calculate the average—the total of the grades divided by the number of grades.

  3. Display the result.

For this example, we’ll place the 10 grades in a list. You also could input the grades from a user at the keyboard (as we’ll do in the next example) or read them from a file (as you’ll see how to do in the “Files and Exceptions” chapter). We also show you how to read data from SQL and NoSQL databases in later chapters.

3.10.2 Pseudocode for the Algorithm

The following pseudocode lists the actions to execute and specifies the order in which they should execute:

Set total to zero
Set grade counter to zero
Set grades to a list of the ten grades

For each grade in the grades list:
        Add the grade to the total
        Add one to the grade counter

Set the class average to the total divided by the number of grades
Display the class average

Note the mentions of total and grade counter. In Fig. 3.1’s script, the variable total (line 5) stores the grade values’ running total, and grade_counter (line 6) counts the number of grades we’ve processed. We’ll use these to calculate the average. Variables for totaling and counting normally are initialized to zero before they’re used, as we do in lines 5 and 6.

3.10.3 Coding the Algorithm in Python

The following script implements the pseudocode algorithm.

Fig. 3.1 | Class average program with sequence-controlled repetition.

 1 # fig03_01.py
 2 """Class average program with sequence-controlled repetition."""
 3
 4 # initialization phase
 5 total = 0  # sum of grades
 6 grade_counter = 0
 7 grades = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94] # list of 10 grades
 8
 9 # processing phase
10 for grade in grades:
11     total += grade  # add current grade to the running total
12     grade_counter += 1  # indicate that one more grade was processed
13
14 # termination phase
15 average = total / grade_counter
16 print(f'Class average is {average}')
Class average is 81.7

Execution Phases

We used blank lines and comments to break the script into three execution phases—initialization, processing and termination:

  • The initialization phase creates the variables needed to process the grades and set these variables to appropriate initial values.

  • The processing phase processes the grades, calculating the running total and counting the number of grades processed so far.

  • The termination phase calculates and displays the class average.

Many scripts can be decomposed (that is, broken apart) into these three phases.

Initialization Phase

Lines 5–6 create the variables total and grade_counter and initialize each to 0. Line 7

grades = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94] # list of 10 grades

creates the variable grades and initializes it with a list of 10 integer grades.

Processing Phase

The for statement processes each grade in the list grades. Line 11 adds the current grade to the total. Then, line 12 adds 1 to the variable grade_counter to keep track of the number of grades processed so far. Repetition terminates when all 10 grades in the list have been processed. This is called definite repetition because the number of repetitions is known before the loop begins executing. In this case, it’s the number of elements in the list grades. The Style Guide for Python Coderecommends placing a blank line above and below each control statement (as in lines 8 and 13).

Termination Phase

When the for statement terminates, line 15 calculates the average and assigns it to the variable average. Then line 16 displays average. Later in this chapter, we use functional-style programming features to calculate the average of a list’s items more concisely.

3.10.4 Introduction to Formatted Strings

Line 16 uses the following simple f-string (short for formatted string) to format this script’s result by inserting the value of average into a string:

f'Class average is {average}'

The letter f before the string’s opening quote indicates it’s an f-string. You specify where to insert values by using placeholders delimited by curly braces ({ and }). The placeholder

{average}

converts the variable average’s value to a string representation, then replaces {average} with that replacement text. Replacement-text expressions may contain values, variables or other expressions, such as calculations or function calls. In line 16, we could have used total / grade_counter in place of average, eliminating the need for line 15.

tick mark Self Check

  1. (Fill-In) A(n) ___________ describes what a program is supposed to do, but not howthe program should do it.
    Answer: requirements statement.

  2. (Fill-In) Many of the scripts you’ll write can be decomposed into three phases: ___________ , ___________ and ___________ .
    Answer: initialization, processing, termination.

  3. (IPython Session) Display an f-string in which you insert the values of the variables number1 (7) and number2 (5) and their product. The displayed string should be

    7 times 5 is 35

    Answer:

    In [1]: number1 = 7
    
    In [2]: number2 = 5
    
    In [3]: print(f'{number1} times {number2} is {number1 * number2}')
    7 times 5 is 35
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.240.178