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
2
solved Python – Division by zero