method to prevent "divided by zero-error"

103 views Asked by At

im running this:

for dataset in waycategory_values:
        if dataset['value'] in [1.0, 2.0, 3.0]: 
            total_highway_distance += dataset['distance']

    for dataset in waycategory_values:
        total_distance += dataset['distance']

    highway_perc = (total_highway_distance / total_distance)

    print(highway_perc)

It is possible that total_distance is zero. Is there a smooth way to keep the script going and just print 0 when the total distance is 0. I was thinking about adding +1 to total_distance everytime - but isn't there a better way?

in my mind the below is circulating, but it's not working:

if total_distance == 0:
    total_distance = 1
1

There are 1 answers

1
Prune On BEST ANSWER

It's "not working" because what the code you wrote doesn't use the logic you say you want. What you described in words looks like this:

# print 0 when the total distance is 0

if total_distance == 0:
    highway_perc = 0
else:
    highway_perc = total_highway_distance / total_distance

print(highway_perc)

You can also do this in one line:

highway_perc = 0 if total_distance == 0 else total_highway_distance / total_distance