Python Forum

Full Version: Overcoming ZeroDivisionError: division by zero Error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In the data set I have 5 such lists (all zero values).

Is there a way I can eliminate this error in such cases? I could simply remove the lists, but don't want to alter the true result.

from ast import literal_eval
 
with open("C:\Dave\data.txt") as f :
    for line in f :
        name, values = line.split(' = ')
        values = literal_eval(values)

print(f" District: {name}")

print(f"Hal received {values[3]} votes AVG: -  {values[3]/sum(values):.2%}).")
District: p3635
Traceback (most recent call last):
File "C:/Python37-32/read.py", line 34, in <module>
print(f"Robert received {values[3]} votes AVG: - {values[3]/sum(values):.2%}).")
ZeroDivisionError: division by zero

The data file is (fails when it hits p3635):

p3624 = [454, 434, 175, 178, 82, 92, 6]
p3635 = [0, 0, 0, 0, 0, 0, 0]
Use a try...except block to provide alternative code when the error arises.

from ast import literal_eval
  
with open("C:\Dave\data.txt") as f :
    for line in f :
        name, values = line.split(' = ')
        values = literal_eval(values)
 
print(f" District: {name}")

try: 
    print(f"Hal received {values[3]} votes AVG: -  {values[3]/sum(values):.2%}).")
except ZeroDivisionError:
    ...
note that this will print info only for last line. You need to print inside the for loop
Hmm, still receive ZeroDivisionError: division by zero, trying the following:

from ast import literal_eval

with open("C:\Dave\data.txt") as f :
    for line in f :
        name, values = line.split(' = ')
        values = literal_eval(values)

        print(f" District: {name}")
        print(f"Hal received {values[3]} votes AVG: -  {values[3] / sum(values):.2%}).")

try :
    print(f"Hal received {values[3]}")
except ZeroDivisionError :
    ...
Traceback (most recent call last):
File "C:/Python37-32/read1.py", line 9, in <module>
print(f"Hal received {values[3]} votes AVG: - {values[3] / sum(values):.2%}).")
ZeroDivisionError: division by zero

I think I am having trouble including the for loop in the code above when division by zero occurs:

#this works
try:
    (print (1/0))
except ZeroDivisionError:
    print ("You can't divide by zero, you're silly.")
try:
    with open("C:\Dave\data.txt") as f :
        for line in f :
            name, values = line.split(' = ')
            values = literal_eval(values)
 
            print(f" District: {name}")
            print(f"Hal received {values[3]} votes AVG: -  {values[3] / sum(values):.2%}).")
except ZeroDivisionError as error:
    print(f'Can\'t divide this: {error}')
To handle the issue, the operation that might throw the exception must happen in the try: block.

In your second example, that's exactly what is shown. There's only one line in the try block, and it's an explicit division by zero. So the except block is entered.

In your first example, the division by zero potentially happens in line 9 (since that's where the division occurs), not line 12 which prints the answer. By then, it's too late.
#! /usr/bin/env python3
from ast import literal_eval

with open('test.txt') as file:
    for line in file:
        name, values = line.split('=')
        values = literal_eval(values)
        if sum(values) == 0:
            pass
        else:
            print(f'District: {name}')
            print(f'Hal received {values[3]} votes AVG: - {values[3]/sum(values):.2%}.')
test.txt
Output:
p3624=[454, 434, 175, 178, 82, 92, 6] p3635=[0, 0, 0, 0, 0, 0, 0] p3628=[45, 44, 175, 178, 82, 92, 6]
Output:
District: p3624 Hal received 178 votes AVG: - 12.53%. District: p3628 Hal received 178 votes AVG: - 28.62%.
(Jun-11-2020, 09:02 PM)dgrunwal Wrote: [ -> ]Hmm, still receive ZeroDivisionError: division by zero, trying the following:

Look at @stullis' example and how it differ from your code:

from ast import literal_eval
   
with open("C:\Dave\data.txt") as f :
    for line in f :
        name, values = line.split(' = ')
        values = literal_eval(values)
  
        print(f" District: {name}")
 
        try: 
            print(f"Hal received {values[3]} votes AVG: -  {values[3]/sum(values):.2%}).")
        except ZeroDivisionError:
            print('There are only zeros in values.'
Note, I don't think values[3]/sum(values) would produce average value, if that is what you calculate AVG
Thank you guys for looking, code working now. Much appreciation,
Dave