How To Resolve ZeroDivisionError: Division By Zero In Python

ZeroDivisionError: division by zero in Python

While programming, you may have experienced the ZeroDivisionError: Division by zero in Python. There are a few suggestions that can help you resolve this error. Read the following article to understand more.

What causes the ZeroDivisionError: division by zero in Python?

You must know that in math, a positive number, a negative number divided by zero, will return undefined results.

ZeroDivisionError: this is a built-in exception that will appear when a number is divisible. Note that you always handle the ZeroDivisionError exception, so your program doesn’t terminate.

The ZeroDivisionError: division by zero happens when you divide a float by 0.

Example:

myNumber1 = 18.0
myNumber2 = 0

print(myNumber1 / myNumber2)

Output:

Traceback (most recent call last):
  File "code.py", line 4, in <module>
    print(myNumber1 / myNumber2)
ZeroDivisionError: float division by zero

How to solve this error?

Use a try/except block

You can use the try-except block to handle the error.

Example:

  • Initialize two variables (the second variable has a value of 0).
  • The code between the first try-except clause is executed. If no exception occurs, only the try clause will run. The except clause will not run. If a ZeroDivisionError exception occurs, only the except clause runs.
myNumber1 = 18.0
myNumber2 = 0

# Use a try/except block to ignore errors
try:
    result = myNumber1 / myNumber2
    print(result)
except ZeroDivisionError:
    print("Change the value of myNumber2. Enter a value that is not 0")

Output:

Change the value of myNumber2. Enter a value that is not 0

Use != operator

You can use the relational operator ‘!=’ for error handling.

The ‘!=’ operator compares the values ​​of the arguments: if they are different, it returns True. If equal, returns False.

Example:

  • Initialize two variables (the second variable has a value of 0).
  • Use the ‘!=’ operator compares ‘myNumber2’ with 0. Otherwise, execute the statement in the if. If zero, execute the statement in else.
myNumber1 = 18.0
myNumber2 = 0

# Use the '!=' operator compares 'myNumber2' with 0
if myNumber2 != 0:
    result = myNumber1 / myNumber2
    print(result)
else :
    print ("Change the value of myNumber2. Enter a value that is not 0")

Output:

Change the value of myNumber2. Enter a value that is not 0

Summary

This article will help you if you encounter the ZeroDivisionError: division by zero in Python. If you have any questions about this issue, leave a comment below. I will answer your questions. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *