0

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 ??

rahdirs
  • 13
  • 1
  • 6
  • Is `mcs` a float or an int? – arshajii Nov 30 '18 at 19:46
  • `delta_mcs_2_gfx_percentage=(delta_mcs_2_gfx*100)/float(mcs) ` doesn't appear in the code snippet you've provided us. The error message tells you where the error is happening, and it's not happening anywhere in that bit of code you've posted. Are you using an IDE with line numbers? Go to line 209. – mypetlion Nov 30 '18 at 19:46
  • 3
    stop using `is` except to compare to `None` – Jean-François Fabre Nov 30 '18 at 19:48
  • @Jean-FrançoisFabre You don't need to use `is` to compare to `None`. This is Python, not SQL. Even though overusing `is` is a common mistake for beginners, that doesn't make it useless. Sometimes you actually do care about distinguishing between whether you're dealing with two equivalent objects or two references to the same object. – mypetlion Nov 30 '18 at 19:51
  • I heard it's "idiomatic" because `None` is a singleton. But `==` also works. You can code without `is` all your carreer. If you have to use `is` to test if it's the same object _in an operational program_, then you have a serious problem – Jean-François Fabre Nov 30 '18 at 19:52

2 Answers2

6

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.

andrew_reece
  • 20,390
  • 3
  • 33
  • 58
1

You are using is when you should be using ==.

is checks for the identical instances. IS this thing the same thing as this other thing

== checks for equality of the same or different instances. Is 0 EQUAL to 0.0?

My bet is that you are checking to see if 0 IS 0.0, which is it not. Then, when you divide by 0.0, you get the Error.

GranolaGuy
  • 133
  • 12