How To Make Division By Zero Return Zero In Python

Make division by Zero return Zero in Python

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:

Leave a Reply

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