Getting past ZeroDivisionError in Python

Viewed 30

So I'm trying to calculate some salary averages based on job types in Python.

I've managed to extract all necessary information from a csv and store them in variables, but when I come to calculating averages, there's a chance that some of the roles don't have any salaries (for example, the csv includes full time ai scientists but not contracted ai scientists). So when I try to calculate the average for a contracted ai scientist - I get a ZeroDivisionError.

I want Python to see the ZeroDivision Error and ignore it and continue computing averages - this doesn't work in a try/except block and I'm not sure where to proceed from here.

This is my code so far:


ft_ai_scientist = 0
count_ft_ai_scientist = 0 
ct_ai_scientist = 0
count_ct_ai_scientist = 0

with open('/Users/xxx/Desktop/ds_salaries.csv', 'r') as f:
    csv_reader = f.readlines()
    for row in csv_reader:
        new_row = row.split(',')
        employment_type = new_row[3]
        job_title = new_row[4]
        salary_in_usd = new_row[7]

        if employment_type == 'FT' and job_title == 'AI Scientist':
            ft_ai_scientist += int(salary_in_usd)
            count_ft_ai_scientist += 1

        if employment_type == 'CT' and job_title == 'AI Scientist':
            ct_ai_scientist += int(salary_in_usd)
            count_ct_ai_scientist += 1

avg_ft_ai_scientist = ft_ai_scientist / count_ft_ai_scientist
avg_ct_ai_scientist = ct_ai_scientist / count_ct_ai_scientist

print(avg_ft_ai_scientist)
print(avg_ct_ai_scientist)

1 Answers

Check to make sure your count of count_ft_ai_scientist and count_ct_ai_scientist are recording the actual counts because it appears your count_ft_ai_scientist and count_ct_ai_scientist are outside the scope of the with_open() function.

Another possible way:

from contextlib import suppress

with suppress(ZeroDivisionError):
  {your code goes here}
Related