19.8. Comparing States

This section uses the same data file that we have been using, but if you want to see all of the data click on the Show button below. Once it appears, you can hide it again by clicking on the Hide button.

We now can calculate the pollution for a particular state. To compare a number of 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:

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.

You have attempted of activities on this page