Make division by zero equal to zero

octosquidopus picture octosquidopus · Dec 5, 2014 · Viewed 92.5k times · Source

How can I ignore ZeroDivisionError and make n / 0 == 0?

Answer

davidism picture davidism · Dec 5, 2014

Check if the denominator is zero before dividing. This avoids the overhead of catching the exception, which may be more efficient if you expect to be dividing by zero a lot.

def weird_division(n, d):
    return n / d if d else 0