newbiecoder
newbiecoder

Reputation: 21

Catch and handle the ZeroDivisionError - python

def divide(divisor, dividend):
  if divisor is not 0:
    return dividend / divisor
  else:
    return 'Division by zero not allowed'
assert divide(0,10) == "Division by zero not allowed"

Is this a suitable method to divide by zero and get a result - (division by zero not allowed)? Or is there an easier way to reach a solution?

When running this code, I get the error Assertion Error: but the error is not defined/ specified. What have I done wrong in this code and how do I fix it!

Upvotes: 0

Views: 1217

Answers (1)

Wrench56
Wrench56

Reputation: 286

For me your code works perfectly. However you can also use try to catch errors. Here is my suggestion:

def divide(divisor, dividend):
    try:
        return divisor / dividend
    except ZeroDivisionError:
        return "Division by zero not allowed"
print(divide(10, 0))

Upvotes: 1

Related Questions