close

[Solved] python : [ZeroDivision: division by zero]

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error python : [ZeroDivision: division by zero] in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How python : [ZeroDivision: division by zero] Error Occurs?

Today I get the following error python : [ZeroDivision: division by zero] in python.

How To Solve python : [ZeroDivision: division by zero] Error ?

  1. How To Solve python : [ZeroDivision: division by zero] Error ?

    To Solve python : [ZeroDivision: division by zero] Error Catch the error and handle it:
    try: z = x / y except ZeroDivisionError: z = 0

  2. python : [ZeroDivision: division by zero]

    To Solve python : [ZeroDivision: division by zero] Error Catch the error and handle it:
    try: z = x / y except ZeroDivisionError: z = 0

Solution 1

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 you’re sure y is a number, which implies it`s truthy if nonzero:

z = (x / y) if y else 0

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read