Handle Division by Zero
In this step, you will learn how to handle division by zero errors in Python. Division by zero is a common error that occurs when you try to divide a number by zero. In mathematics, division by zero is undefined, and in programming, it typically results in an error that can crash your program.
Let's see what happens when we try to divide by zero in Python:
## Create a script named division_error.py
## Open VS Code editor and create a new file named division_error.py in ~/project directory
## Add the following content to the file
numerator = 10
denominator = 0
result = numerator / denominator
print(result)
Save this code as division_error.py
in your ~/project
directory. Now, let's run the script:
cd ~/project
python division_error.py
You should see an error message like this:
Traceback (most recent call last):
File "/home/labex/project/division_error.py", line 4, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
The ZeroDivisionError
indicates that we have attempted to divide by zero. To prevent this error from crashing our program, we can use error handling techniques. One common approach is to use a try-except
block:
## Create a script named safe_division.py
## Open VS Code editor and create a new file named safe_division.py in ~/project directory
## Add the following content to the file
numerator = 10
denominator = 0
try:
result = numerator / denominator
print(result)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
Save this code as safe_division.py
in your ~/project
directory. Now, let's run the script:
cd ~/project
python safe_division.py
You should see the following output:
Error: Cannot divide by zero
In this example, the try
block attempts to perform the division. If a ZeroDivisionError
occurs, the except
block is executed, which prints an error message instead of crashing the program.
Another approach is to check if the denominator is zero before performing the division:
## Create a script named check_division.py
## Open VS Code editor and create a new file named check_division.py in ~/project directory
## Add the following content to the file
numerator = 10
denominator = 0
if denominator == 0:
print("Error: Cannot divide by zero")
else:
result = numerator / denominator
print(result)
Save this code as check_division.py
in your ~/project
directory. Now, let's run the script:
cd ~/project
python check_division.py
You should see the following output:
Error: Cannot divide by zero
Both of these approaches allow you to handle division by zero errors gracefully and prevent your program from crashing. Choose the approach that best suits your needs and coding style.