Home > Back-end >  Python - Division by zero
Python - Division by zero

Time:05-07

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

CodePudding user response:

You can use or:

n = 0
5/(n or 1)

CodePudding user response:

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

CodePudding user response:

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
  • Related