Zeno
Zeno

Reputation: 65

Python: How to manage ZeroDivisionError

I'm very new to Python and I'm struggling with this error, here is my code:

new_dictionary = dict(((i,f), abs(int(-d/-(-first_dictionary[i, f]//second_dictionary[i, f])))) for i in I for f in F)

I get in return this: ZeroDivisionError: float division by zero

I know that this error occurs because some values of first_dictionary and of second_dictionary are equal to 0.0, but I don't know how to manage it.

I tried to define this function:

def my_function(dict1, dict2):
    first_dictionary = dict1
    second_dictionary = dict2
    for i in I:
        for f in F:
            if first_dictionary[i, f] == 0 or second_dictionary[i, f] == 0.0:
                new_value = 0
            else:
                new_value = abs(int(-d/-(-first_dictionary[i, f]//second_dictionary[i, f])))
    return new_value


new_dictionary = dict(((i, f), my_function(first_dictionary, second_dictionary)) for i in I for f in F)

But the output is different from what I expected, it gives me the same value for all key in the dictionary.

How can I resolve this error? Thanks in advance!

Upvotes: 0

Views: 348

Answers (2)

zwer
zwer

Reputation: 25789

You don't need to do two loops, if you want explicit check instead of error capture:

def safe_division(a, b):
    if not b:
        return 0
    return a / b

new_dictionary = dict(((i,f), abs(int(safe_division(-d, safe_division(-first_dictionary[i, f], second_dictionary[i, f]))))) for i in I for f in F)

Actually, let's make it a tad bit better with dict comprehension:

new_dictionary = {(i, f): abs(int(safe_division(-d, safe_division(-first_dictionary[i, f], second_dictionary[i, f])))) for i in I for f in F}

Upvotes: 1

Aditya
Aditya

Reputation: 2520

Source - Reference

>>> try:
    ...     f(0)
    ... except ZeroDivisionError:
    ...     import traceback
    ...     traceback.print_last()
    ... 
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>

You can use this to check the first instance of what is causing the error

Upvotes: 1

Related Questions