Skip to content
Advertisement

Error python : [ZeroDivisionError: division by zero]

I faced an error when I run my program using python: The error is like this:

JavaScript

My program is similar to this:

JavaScript

Thus, I want to ask, how to avoid that error in python. My desired output is z = 0

Advertisement

Answer

Catch the error and handle it:

JavaScript

Or check before you do the division:

JavaScript

The latter can be reduced to:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement