 # How To Make Division By Zero Return Zero In Python ## 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.

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.

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.

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: