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
Wrap it in try-except
The above code can be reduced to:
Reproducing the error
Output:
You can solve the ZeroDivisionError by the following ways:
Wrap it in try except
Check before you do the division
The above code can be reduced to:
Different Variation
In Python, the Zero Division Error:division by zero is thrown in various forms in different contexts. They are given below:
- ZeroDivisionError: division by zero
- ZeroDivisionError: float division by zero
- ZeroDivisionError: integer division or modulo by zero
- ZeroDivisionError: long division or modulo by zero
- ZeroDivisionError: complex division by zero
- TypeError: 'NoneType' object is not subscriptable
- IndexError: string index out of range
- IndentationError: unexpected indent Error
- ValueError: too many values to unpack (expected 2)
- SyntaxError- EOL while scanning string literal
- TypeError: Can't convert 'int' object to str implicitly
- IndentationError: expected an indented block
- ValueError: invalid literal for int() with base 10
- IndexError: list index out of range : Python
- AttributeError: 'module' object has no attribute 'main'
- UnboundLocalError: local variable referenced before assignment
- TypeError: string indices must be integers
- FileNotFoundError: [Errno 2] No such file or directory
- Fatal error: Python.h: No such file or directory
- ImportError: No module named requests | Python
- TypeError: 'NoneType' object is not iterable
- SyntaxError: unexpected EOF while parsing | Python
- zsh: command not found: python
- Unicodeescape codec can't decode bytes in position 2-3
- The TypeError: 'tuple' object does not support item assignment
- The AttributeError: 'bytes' object has no attribute 'read'