Robert Grootjen
Robert Grootjen

Reputation: 197

Why is my "if" statement not excluding zeros?

I have to divide here some values, but since it's zero it will give a "ZeroDivisionError". So I coded the following.

if list_actual_revenue[x] != 0.00 or list_actual_revenue[x] != 0:
    print('********************')
    print(list_actual_revenue[x])
    print('********************')
    value_rev = float(list_forecast_revenue[x]) - float(list_actual_revenue[x])
    value_rev = value_rev / float(list_actual_revenue[x])

The error I'm getting is

    value_rev = value_rev / float(list_actual_revenue[x])
ZeroDivisionError: float division by zero

So I decided to print out the values and see what's happening

********************
3120.00
********************
********************
3055.00
********************
********************
11625.00
********************
********************
11937.50
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
3000.00
********************
********************
0.00
********************

As you can see the last line is "0.00". My question is: Why is the 0.00 there if the "if statement" has to exclude it?

Upvotes: 0

Views: 251

Answers (1)

Arutyun Enfendzhyan
Arutyun Enfendzhyan

Reputation: 1909

Yeah, I can feel your pain. If you are using floating point, then you should never use "==" or "!=" operators. Instead, try checking if the absolute value of list_actual_revenue[x] > 0.

Or you can try catching the error and then handling the zero case like here: Error python : [ZeroDivisionError: division by zero]

Upvotes: 1

Related Questions