'Python - Division by zero
how can i make something divided by 0 equal base, EX:
5/0 output 5
Sorry I can't explain properly, I'm new to programming
Solution 1:[1]
There are 3 ways to do this, the normal way I do it is like this. Note this will also output 5 if n is negative. I typically use this when averaging collections that might be empty, since negative lengths are impossible.
result = 5/max(1, n)
Will output 5 if n is 0 or negative. Very compact and useful in big equations.
Other way with if:
if n!=0:
result = 5/n
else:
result = 5
Or with try:
try:
result = 5/n
except ZeroDivisionError:
result = 5
Solution 2:[2]
You can use or:
n = 0
5/(n or 1)
Solution 3:[3]
Whilst the requirement is mathematically incorrect, this is best dealt with by wrapping the implementation in a function.
def divide(x, y):
return x if y == 0 else x / y
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | trincot |
| Solution 3 | Albert Winestein |
