ZeroDivisionError: float division | Python

In mathematics, any non-zero number either positive or negative divided by zero is undefined because there is no value. The reason is that the result of a division by zero is undefined is the fact that any attempt at a definition leads to a contradiction.

ZeroDivisionError

The super class of ZeroDivisionError is ArithmeticError. ZeroDivisionError is a built-in Python exception thrown when a number is divided by 0. This means that the exception raised when the second argument of a division or modulo operation is zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws "ZeroDivisionError" error if the result is infinite number. While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate.

Handling ZeroDivisionError in Python


How to Make Division by Zero to Zero in Python?
Wrap it in try-except
try: z = x / y except ZeroDivisionError: z = 0
Or check before you do the division:
if y == 0: z = 0 else: z = x / y

The above code can be reduced to:

z = 0 if y == 0 else (x / y)

Reproducing the error

x = 5 y = 0 z = x/y print(z)

Output:

Traceback (most recent call last): File "./prog.py", line 3, in <module> ZeroDivisionError: division by zero

You can solve the ZeroDivisionError by the following ways:

Wrap it in try except

x = 5 y = 0 try: z = x/y except ZeroDivisionError: z=0 //handle here print(z) //output as 0

Check before you do the division

x = 5 y = 0 if y == 0: z = 0 else: z = x / y print(z) //output as 0

The above code can be reduced to:

x = 5 y = 0 z = 0 if y == 0 else (x / y) print(z) //output as 0

Different Variation

In Python, the Zero Division Error:division by zero is thrown in various forms in different contexts. They are given below:

  1. ZeroDivisionError: division by zero
  2. ZeroDivisionError: float division by zero
  3. ZeroDivisionError: integer division or modulo by zero
  4. ZeroDivisionError: long division or modulo by zero
  5. ZeroDivisionError: complex division by zero