Search code examples
pythonfloatinginteger-divisiondivide-by-zero

ZeroDivisionError: float division by zero even though I have a zero catcher


I'm a little new to Python. I have attached a snippet of code below. constant_a & b are integers. While running this code, I get the following error:

Traceback (most recent call last): File "U:\V10_run2\process.py", line 209, in delta_mcs_2_gfx_percentage=(delta_mcs_2_gfx*100)/float(mcs) ZeroDivisionError: float division by zero

mcs=hash["MCF"]*constant_a/constant_b  

if mcs is 0:
      delta__percentage=-100
else:
      delta__percentage=(delta*100)/mcs

As the error says I thought this was because python was trying to do a integer division & rounding mcs to 0 but I also tried float(delta*100)/float(mcs) which didn't help as well. Any suggestions ??


Solution

  • Try using == instead of is:

    a = 0.0
    
    if a is 0:
        print("is zero")
    else:
        print("not zero")
    # 'not zero'
    
    if a == 0:
        print("== zero")
    else:
        print("not zero")
    # '== zero'
    

    See this post for a bit more explanation. Essentially, == tests for equality and is tests for exact object identity.