A ZeroDivisionError occurs when a program attempts to divide a number by 0. Since division by zero is mathematically undefined, Python immediately stops the program and raises this exception. This error commonly occurs when the denominator is calculated dynamically, received from user input, or obtained from external data without proper validation.
a = 20
b = 0
print(a/b)
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
ZeroDivisionError: division by zero
Explanation: a/b attempts to divide 20 by 0. Since Python does not allow division by zero, it raises a ZeroDivisionError.
Common Causes of ZeroDivisionError
A ZeroDivisionError is usually caused by one of the following situations:
- Dividing by a literal zero: Directly writing an expression such as 10/0.
- Using a variable with value 0: The denominator is stored in a variable that happens to contain 0.
- User input: The user enters 0 as the divisor.
- Calculated denominator: A calculation or formula unexpectedly produces 0 before division is performed.
- Data from files or databases: External data contains zero values that are used as divisors without validation.
Handling ZeroDivisionError
1. Check the Denominator Before Dividing: Before performing division, verify that the denominator is not zero.
a = 15
b = 5
if b != 0:
print(a / b)
else:
print("Cannot divide by zero.")
Output
3.0
Explanation: The if statement checks whether b is zero. Division is performed only when the denominator is valid.
2. Handle the Exception Using try-except: If the denominator may become zero during program execution, use a try-except block.
a = 16
b = 0
try:
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
Output
Cannot divide by zero.
Explanation: When a/b raises a ZeroDivisionError, execution moves to the except block instead of terminating the program.
3. Handle User Input Safely: When the denominator comes from user input, handle both invalid values and division by zero.
a = 18
try:
b = int(input("Enter a number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid integer.")
Output
Enter a number: 0
Cannot divide by zero.
Explanation:
- ZeroDivisionError is raised if the user enters 0.
- ValueError is raised if the input is not a valid integer.
- The exception handlers prevent the program from crashing.
4. Use a Default Value When Division Is Not Possible: If division cannot be performed, you can assign a default value instead.
a = 25
b = 0
res = a / b if b != 0 else 0
print(res)
Output
0
Explanation: The conditional expression checks whether b is zero. If it is, 0 is assigned to result; otherwise, the division is performed.