This article can help you learn how to make division by Zero return Zero in Python. Let’s follow this article to learn more about it with the explanation and examples below.
Make Division By Zero Return Zero In Python
When working with the Number in Python, you can easily encounter the Error: ZeroDivisionError: division by zero in Python when dividing a Number with zero.
But you want to assign the value as 0 when this Error occurs. There are some solutions that can help you make division by Zero return Zero in Python. To do that, you can check if the dividend is 0 or not before dividing two numbers. You can also use the try-except method in Python. Another solution is using the ‘and’ operator.
Use the if statement
You can use the if statement to check if the dividend is 0 or not before dividing two numbers.
Look at the example below to learn more about this solution.
def division(value1,value2): # Check if the dividend is 0 or not before dividing two Numbers if value2 == 0: return 0 # If the divident is not 0, the function will return this value return value1/value2 print(division(10,5)) print(division(10,0))
Output
2.0
0
Use the try-except method
You can use the try-except method to avoid the Error: ZeroDivisionError: division by zero if the dividend is 0. If the error occurs, the function will return 0. In this way, you can make division by zero return zero.
Look at the example below to learn more about this solution.
def division(value1,value2): try: result = value1/value2 return result except ZeroDivisionError: # If the dividend is 0, the function will return 0 return 0 print(division(10,5)) print(division(10,0))
Output
2.0
0
Use the and operator
The and operator returns the first parameter when it is falsy, otherwise returns the second parameter.
Look at the example below to learn more about this solution.
def division(value1,value2): return value2 and value1/value2 print(division(10,5)) print(division(10,0))
Output
2.0
0
Summary
These are some solutions that can help you make division by Zero return Zero in Python. To do that, you can use the if statement to check if the dividend is 0 or not before dividing two numbers or the try-except method. Choose the solution that is the most suitable for you. We hope this tutorial is helpful for you. Thanks!
Maybe you are interested:
- How to remove the division decimal in Python
- Add zeros to a float after the decimal in Python
- Force division to return a floating-point number in Python

My name is Thomas Valen. As a software developer, I am well-versed in programming languages. Don’t worry if you’re having trouble with the C, C++, Java, Python, JavaScript, or R programming languages. I’m here to assist you!
Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Java, Python, JavaScript, R