18.4. What’s the largest pollution values?

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.

One of the interesting questions to explore is, “Which city has the worst pollution?” The program below figures that out for the PM 2.5 value. It will read all the data in, then set max25 (the maximum PM 2.5 value) to zero. It will then loop through all the city data and if the current pollution (in new25) is greater than max25, it will save that value in max25 and save that city name as maxCity. We need the float function to convert the string into a number that we can compare.

Replace the lines that start with a comment (a #) below to find the city with the highest PM 10 pollution.

The following program prints the maximum PM 2.5 pollution found, but the code is mixed up. Drag the blocks of statements from the left column to the right column and put them in the right order. Then click on <i>Check Me</i> to see if you are right. You will be told if any of the lines are in the wrong order or have the wrong indention.

        # read all the lines
inFile = open("uspoll.txt","r")
lines = inFile.readlines()
inFile.close()

# initialize the variables
maxCity = ''
max25 = 0
---
# loop through the lines
for line in lines:
---
    # split at :
    values = line.split(":")
---
    # get the PM 2.5 pollution
    new25 = float(values[2])
---
    # if current > max
    if new25 > max25:
---
        # save the new max info
        maxCity = values[0]
        max25 = new25
---
# print the largest PM 2.5 value
print("Largest is ",max25," in ",maxCity)
        

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page