In Python, division by zero generates the exception ZeroDivisionError: division by zero. This is because in mathematics, division by zero is undefined.
>>> 7 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>>
Today we’ll go over some ways to avoid the zero division error in Python and force it to return a zero.
- First, we’ll look into exception handling in Python.
- Second, we’ll examine different ways to check for a zero denominator with an
- Third, we’ll learn about a conditional expression, also known as a Python ternary operator.
- Fourth, we’ll look at a solution using the Python logical operators
or, and specifically taking advantage of their short-circuiting feature.
Method 1: Exception Handling
A common way to deal with errors or exceptions in programming is with exception handling.
In Python, we use a
try block that contains a return statement to divide 2 numbers. If there is no division by zero error, then it will return the result.
except line will check if the specified exception name is a match, and then it will execute the code under the except block. In this case, we’re telling it to return 0.
Let’s define a function as an example called
zero_div(x, y) which accepts two parameters –
x for the numerator and
y for the denominator.
>>> def zero_div(x, y): ... try: ... return x / y ... except ZeroDivisionError: ... return 0 ... >>> zero_div(100, 25) 4.0 >>> zero_div(99, 0) 0 >>> zero_div(99, 9) 11.0 >>> zero_div(2021, 0) 0 >>>
As we can see, each time we call the function it will return the result of the division, or a zero if a
Before we continue, I feel that I should mention this exception handling method falls into the common Python coding practice labeled EAFP – easier to ask for forgiveness than permission. It is considered as a best practice, however, there’s no harm in seeing the other ways of solving this problem, right? And if you’re wondering, there’s also a label for using
if statements to make these checks to try to avoid the exception error – LBYL: look before you leap. With that said, let’s move on.
If you love Python one-liners (like me), then here’s a way to code the division by zero exception handling. We’ll make use of the Python built-in function
exec(). We must pass in the
try-except block as a string. If there’s no division by zero, then we’ll print the result. Otherwise, it will print zero.
So how do we compose a string version of the
try: print(x / y) except ZeroDivisionError: print(0)
As long as you remember to insert the newline character
"\n" after the first line, then you should be OK.
Below examples run the code a few times. Note I used actual numerical values for the numerator and denominator instead of variables.
>>> exec('try: print(9/2) \nexcept ZeroDivisionError: print(0)') 4.5 >>> exec('try: print(9/0) \nexcept ZeroDivisionError: print(0)') 0 >>> exec('try: print(72/9) \nexcept ZeroDivisionError: print(0)') 8.0 >>> exec('try: print(72/0) \nexcept ZeroDivisionError: print(0)') 0 >>>
Read more about Python one line exception handling.
Method 2: Check for a Zero Denominator
Let’s avoid the error altogether and just check if the denominator is a zero, shall we? We can accomplish this with the following code that uses an
if statement. Let’s define a function again,
>>> def zero_div(x, y): ... if y: return x / y ... else: return 0 ... >>> zero_div(100, 50) 2.0 >>> zero_div(100, 0) 0 >>> zero_div(525, 50) 10.5 >>> zero_div(525, 0) 0 >>>
As shown above, within the function we are first checking if the variable “
True. In Python, the number 0 is evaluated to
False, and all other numbers are evaluated as
True. A quick example using the built-in
>>> bool(0) False >>> bool(500) True >>> bool(3) True >>> bool(-19) True >>>
As long as the variable “
y” is not zero, then return the evaluation of
x / y. Otherwise, return 0.
An alternative to the above is to use the Python ternary operator. Let’s re-code the function as follows:
>>> def zero_div(x, y): ... return x / y if y else 0 ... >>> zero_div(88, 8) 11.0 >>> zero_div(88, 0) 0 >>> zero_div(8, 4) 2.0 >>> zero_div(42, 0) 0 >>>
As you can see, we’re still checking for a
True value for the denominator, “
y”. If so, then it will return the evaluation of
x / y. If “
False, or zero, then 0 is returned.
Method 3: Short-Circuit Operators
The last method we’ll go over makes use of the short-circuiting feature that is built into the
and operator, if the first operand is evaluated as
True, then the second operand is returned. But if the first operand is
False, then it does not evaluate the second operand and returns
or operator, if the first operand is
True, then it doesn’t evaluate the second operand and returns the first operand. If the first operand is
False, then it returns the second operand.
Let’s rewrite our
zero_div function one last time:
>>> def zero_div(x, y): ... return y and x / y or 0 ... >>> zero_div(28, 7) 4.0 >>> zero_div(28, 0) 0 >>>
Let’s look at the logical expression step by step when passing 28 and 7 into the function.
We will rewrite “
y and x / y or 0” as:
7 and 28/7 or 0
7 is evaluated as
True and 28/7 or 0
Applying the short-circuiting feature for the
and expression, since the first operand is
True, then the second operand is returned. And we get the following:
28/7 or 0
Now let’s apply the short-circuiting feature for the
or expression. The first operand is not
False, therefore it is returned without evaluating the second operand. And we are left with
28/7, which is finally evaluated to
Now let’s examine the next function call where
x is 28 and
y is 0.
0 and 28/0 or 0 – this will evaluate to:
False and 28/0 or 0
and short-circuit operation, since the first operand is
False is returned straightaway without evaluating the second operand and we’re left with:
False or 0
Finally, for the
or short-circuit, since the first operand is
False, then the second operand is returned which is 0.
Today we looked at three different methods to ignore the zero division error in Python and instead have it return a zero. The first method is the preferred way which uses exception handling. Second, we checked for a zero denominator by using Python’s ternary operator and also the standard if statement. And lastly, we took advantage of the short-circuit operations that are built into the logical operators.
Which method would you choose? And what type of coder are you? Do you agree that it’s easier to ask for forgiveness than permission, or are you more of a look before you leap hacker? In any case, I would like to thank you for taking the time to explore this topic with me, and I’ll be seeing you in the next one! Bye for now.