Skip to main content

Section 31.8 Comparing States

We now can calculate the pollution for a particular state. To compare several states, we can run the program once for each state. But it would be nice to run the program just once and have it repeat the calculations for each state that we are concerned about.
To do this, we need to be able to easily repeat the “find average pollution” logic. If we have a large amount of code that we want to repeat, it makes sense to turn it into a function. The function getAvgPM25 will take in a targetState and the data collection. It will then do the work to calculate the average and return it. There are some print calls in the function just to show us what data is being worked on to help confirm the code is working. In the main part of the program, we call the function twice - once for “OR” and once for “TX”.
If we have a large list of states we want to process, it would be silly to keep copy/pasting the last three lines of code for different state codes. Repeating those three lines over and over is the perfect job for a loop. Let’s write a loop that can iterate through a list of states:

Checkpoint 31.8.2.

Write a loop to print out each state in stateList on its own line. Do not print anything other than the state codes.
Now we can use your code to help find the average pollution for a large number of different states. Add your loop to the main part of the program below and make sure your loop runs the two lines shown in comments (you may have to adjust the variable name state so it matches your loop). stateList has a list of the three richest (MD, AK, NJ) and poorest states (AK, WV, MS) by per capita income.

Checkpoint 31.8.3.

    What does the program reveal?
  • The richer states seem to be more polluted.
  • Correct
  • The poorer states seem to be more polluted.
  • The poorer states are AR, WV, and MS
  • There does not seem to be a pattern to the results.
  • The poorer states are AR, WV, and MS
You have attempted of activities on this page.