How do I return or print an attribute that's a math function between two attributes? Python

Viewed 49

I'm very new to Python and have checked the three other posts about this subject but haven't been able to implement them successfully.

Essentially, I'm trying to return the name of the county with the highest voter turnout and the percentage. I can't seem to figure out how to return or print the latter part, as I don't have an attribute for the math portion (voters / population).

I've played around with some things like:

def percentage(self, turnout):
  self.turnout = voters / population

Sorry if this post does not format correctly — this is all very new! Thanks in advance.

class County: 
  def __init__(self, name, population, voters):
    self.name = name
    self.population = population
    self.voters = voters

def highest_turnout(data):

  highest_county = data[0]
  highest_percentage = (data[0].voters / data[0].population)

  for county in data:
    if (county.voters / county.population) > highest_percentage:
      highest_county = county
      highest_percentage = (county.voters / county.population)
  return highest_county.name

  
  # implement the function here


# your program will be evaluated using these objects 
# it is okay to change/remove these lines but your program
# will be evaluated using these as inputs
allegheny = County("allegheny", 1000490, 645469) # this is an object
philadelphia = County("philadelphia", 1134081, 539069)
montgomery = County("montgomery", 568952, 399591)
lancaster = County("lancaster", 345367, 230278)
delaware = County("delaware", 414031, 284538)
chester = County("chester", 319919, 230823)
bucks = County("bucks", 444149, 319816)
data = [allegheny, philadelphia, montgomery, lancaster, delaware, chester, bucks]  

result = highest_turnout(data) # do not change this line!
print(result) # prints the output of the function
# do not remove this line!
2 Answers

You simply return multiple values:

return highest_county.name, highest_percentage

In your calling program:

best_county, best_pct = highest_turnout(data)

What's very cool in python is you can actually just write the following:

highest_turnout = max(data, key=lambda county: county.voters / county.population)

Here, highest_turnout is the county with the highest turnout. What we've done is told python to calculate the maximum of the dataset where the values being compared is voters/population ie: the percentage of voters that came. In other words, this does exactly what your highest_turnout function does in a single line. You might consider defining a method for your County class called get_turnout() which just returns the percentage of the population that voted.

Obviously with highest_turnout we can write

highest_turnout.name

and

highest_turnout.voters / highest_turnout.population

to have the values you seek.

Related