Error python : [ZeroDivisionError: division by zero]

Error python : [ZeroDivisionError: division by zero]

Catch the error and handle it:

try:
    z = x / y
except ZeroDivisionError:
    z = 0

Or check before you do the division:

if y == 0:
    z = 0
else:
    z = x / y

The latter can be reduced to:

z = 0 if y == 0 else (x / y) 

Or if youre sure y is a number, which implies it`s truthy if nonzero:

z = (x / y) if y else 0
z = y and (x / y)   # alternate version
# we are dividing until correct data is given
executed = False
while not executed:
    try:
        a = float(input(first number --> ))
        b = float(input(second number --> ))
        z = a / b
        print(z)
        executed = True
    except ArithmeticError as arithmeticError:
        print(arithmeticError)
    except ValueError as valueError:
        print(valueError)
    except Exception as exception:
        print(exception)

Error python : [ZeroDivisionError: division by zero]

Leave a Reply

Your email address will not be published. Required fields are marked *