Python - How to Handle Division by Zero
How would you handle division by zero in Python? You could approach this in a few different ways.
Here we just test if the denominator is 0 and if it is, we silently return 0:
def function1(n, d):
if d == 0:
return 0
return n / d if d else 0
Here we test the denominator, then we print an error message and exit with error status if it is zero:
def function1(n, d):
if d == 0:
print("ERROR - Division by zero!!!")
exit(1)
return n / d if d else 0
Here we use exception handling and silently return 0:
def function2(n, d):
try:
return n/d
except ZeroDivisionError as e:
return 0
Here we use exception handling, print the exception text, and exit with error status:
def function2(n, d):
try:
return n/d
except ZeroDivisionError as e:
print(e)
exit(1)
You can try passing a normal denominator or a zero denominator:
print(function1(8, 2))
print(function1(8, 0))