Programming Tutorial Four

This example will use what we use in the previous 3 examples, but we will add 2 important features:
  1. Instead of having a fixed number of cars to process, we will let the user determine how many cars to process.
  2. Since we could have a big list of cars to output we will clean up the output by using a tabular output arrangement.

Program Description

Input -- Same as last program:
Your program will request the following information from the user:
  1. The make of the car
  2. The odometer reading when the test begins (In whole miles)
  3. The odometer reading when the test ends (In whole miles)
  4. The number of gallons used (To the tenth of a gallon)
Calculation:
Your program will perform the following calculations:
  1. The total miles the car traveled in the test (for each car)
  2. Calculate the Miles Per Gallon (MPG) for each car
  3. Determine if the car is a fuel economy car (gets 30 MPG or more)
  4. Calculate the total Miles Per Gallon of all cars
  5. Calculate the average Miles Per Gallon of all cars
Output:
Your program will output the following data:
  1. A row of column titles
  2. One row for each car entered
  3. Each car data row will contain: Make, Total Miles, MPG and The Economy Flag
  4. A line at the end indicating the number of cars processed and the average Miles Per Gallon of all the cars entered

Creating the Program

While all the steps and code you need to create this program are included in this example, you may wish to see a more complete list of commands. This link will take you to the Python Command Reference.
  • Click this link to see the PythonTutorialFour.python starter file
  • Copy the contents into notepad
  • Save the notepad file using the name PythonTutorialFour.py on to your student disk
  • Open the file using the notepad application (TextEdit if you are on a Mac)
  • Your file should look something like this ---->
Add the new variables needed for the new functionality of program 3
  • Enter the code shown below after the comment that says "Initialize Variables"

    carType = [0,0,0,0,0,0,0,0,0,0]               # Holds the Car Types
    startMiles = [0,0,0,0,0,0,0,0,0,0]            # Holds the starting odometer readings
    endMiles = [0,0,0,0,0,0,0,0,0,0]             # Holds the ending odometer readings
    gallonsUsed = [0,0,0,0,0,0,0,0,0,0]         # Holds the number of gallons used
    totalMiles = [0,0,0,0,0,0,0,0,0,0]            # Holds the total miles driven
    milesPerGallon = [0,0,0,0,0,0,0,0,0,0]    # Holds the miles per gallon
    carMessage = [0,0,0,0,0,0,0,0,0,0]         # Holds the economy designation
    carIndex = 0                                           # Holds the counter for the "for" loop
    mpgAccumulator = 0                              # Holds the total mpg for all cars
    averageMPG = 0                                    # Holds the average mpg for all cars
    carsRented = 0                                      # Holds the number of cars rented

  • Notice that we have taken a new approach in storing variables here. We are using something called an Array (or list in Python). Not only does it allow us to store several pieces of like information together, we can use the loop index variable to help us store in a structured grid.
It is common for a program to have some sort of title that tells the user what the program does and it might include the name of the person (or Company) who wrote the program.
  • Enter the code shown below after the comment that says "Print a title for the report"

    print("\n Your Name - CS 5 - Programming Example 4")   # The \n is a new line
    print("\n")
    print("\n Average MPG across multiple cars")
    print("\n")
The user input data will be a little different since we are now using an Array (or list)
  • Enter the code shown below after the comment that says "Get User Input Data"

       carType[carIndex] = input("Enter make of car: ")
       startMiles[carIndex] = int(input("Enter beginning odometer reading: "))
       endMiles[carIndex] = int(input("Enter ending odometer reading: "))
       gallonsUsed[carIndex] = float(input("How many gallons? "))
Be sure to notice that these are indented. It will not work without the indent.
It is now time for the program to do some calculations. As it turns out we have 2 kinds of calculations in this program: 1) a calculation of user input data and 2) a calculation of a variable that has itself been calculated by this program. The first type of calculation I can do whenever I want to but I must do the 2nd type of calculation after I have performed the calculation required as its input. Lets see what I mean:
  • Enter the code shown below after the comment that says "Compute Calculated Values"

       totalMiles[carIndex] = endMiles[carIndex] - startMiles[carIndex]
       milesPerGallon[carIndex] = totalMiles[carIndex] / gallonsUsed[carIndex]
       mpgAccumulator = mpgAccumulator + milesPerGallon[carIndex]
       if milesPerGallon[carIndex] > 30:
         carMessage[carIndex] = "Yes"
       else:
         carMessage[carIndex] = "No"
Notice the role that the carIndex variable now plays in this program.
Now we are really going to do something different. We are going to use Python's text formatting syntax to create a tabular output. This next section of code creates the column labels. Each field is 18 spaces wide and the first one is left justified.
  • Enter the code shown below after the comment that says "Print Column Headings"

    print()
    print("%-18s" % "Make of Car: " , end=" ")
    print("%18s" % "Miles Driven: " , end=" ")
    print("%18s" % "Miles Per Gallon: " , end=" ")
    print("%18s" % "Ecomony: ")
    print()
We will once again make use of the "for" loop and the carIndex variable to output all the information we stored in our array.
  • Enter the code shown below after the comment that says "Print Detail Lines"

       print("%-18s" % carType[carIndex] , end=" ")
       print("%18d" % totalMiles[carIndex] , end=" ")
       print("%18d" % milesPerGallon[carIndex] , end=" ")
       print("%18s" % carMessage[carIndex])
One last set of information to print. The following code prints the summary and average information.
  • Enter the code shown below after the comment that says "Print Summary Reports"

    print()
    averageMPG =mpgAccumulator / carsRented
    print("Report Summary: " ,carsRented," cars were processed with an average mileage value of")
    print(averageMPG, ".")
  • Save your program to your student disk. Change the name of the program so you know this is the completed version. Note: Be sure the name ends with ".py" - this is what lets the Python Interpreter identify and run your program.

Testing Your Program

  • Here is an example of what you should see:
Now you are ready to try the fourth program assignment. It functions alot like this example so use this example as a tool to help you complete assignment 4.

Return to CS5 Examples Page