Borislav Hadzhiev
Fri Apr 22 2022·2 min read
Photo by Jackson David
The Python "ZeroDivisionError: float division by zero" occurs when we try to
divide a floating-point number by 0
. To solve the error, use an if
statement
to check if the number you are dividing by is not zero, or handle the error in a
try/except
block.
Here is an example of how the error occurs.
a = 15.0 b = 0 # ⛔️ ZeroDivisionError: float division by zero result = a / b
It's unclear what value is expected when we divide by 0
, so Python throws an
error.
When we divide a number by 0
, the result tends towards infinity.
One way to solve the error is to check if the value we are dividing by is not
0
.
a = 15.0 b = 0 if b != 0: result = a / b else: result = 0 print(result) # 👉️ 0
We check if the b
variable doesn't store a 0
value and if it doesn't, we
divide a
by b
.
result
variable to 0
. Note that this could be any other value that suits your use case.If setting the result
variable to 0
, if b
is equal to 0
suits your use
case, you can shorten this to a single line.
a = 15.0 b = 0 result = b and a / b print(result) # 👉️ 0
The expression x and y
first evaluates x
, and if x
is falsy, its value is
returned, otherwise, y
is returned.
0
is a falsy value, it gets returned if the b
variable in the example stores a 0
value, otherwise the result of dividing a
by b
is returned.Alternatively, you can use a try/except
statement.
a = 15.0 b = 0 try: result = a / b except ZeroDivisionError: result = 0 print(result) # 👉️ 0
We try to divide a
by b
and if we get a ZeroDivisionError
, the except
block sets the result
variable to 0
.
The best way to solve the error is to figure out where the variable gets
assigned a 0
and check whether that's the expected behavior.
Here are some common ways you might get a zero value unexpectedly.
print(int()) # 👉️ 0 print(int(0.9)) # 👉️ 0