I need to distinguish when a variable is 0.0 specifically, so a == 0
will not work because it will fail when a
is equal to False. What's the best way to accomplish this?
Asked
Active
Viewed 713 times
0

hoffee
- 470
- 3
- 16
-
related: https://stackoverflow.com/questions/27431249/python-false-vs-0 not a duplicate though because of the float issue – Tomerikoo Apr 16 '20 at 16:29
-
I'm interested in why exactly you need to make the distinction. It suggests that the design can be improved. – Karl Knechtel Apr 16 '20 at 16:38
-
It's actually just for a programming challenge, identifying 0's in an array that includes items like 0, 0.0, False, "0", etc. – hoffee Apr 16 '20 at 16:40
4 Answers
2
Try this:
a = 0.0
if a == 0.0 and isinstance(a, float):
print('a is 0.0')
Or a bit less strict (doesn't care if a
is not a floating value):
a = 0
if a == 0 and a is not False:
print('a is zero')

Óscar López
- 232,561
- 37
- 312
- 386
-
Note that `a == 0 and a is not False` can be chained with `0 == a is not False`. – blhsing Apr 16 '20 at 17:06
-
@blhsing TBH that doesn't look like an improvement, I'm still trying to parse in my head _why_ that would work, you'd need to know by heart the operator precedence rules. Let's not sacrifice readability for typing less code. – Óscar López Apr 16 '20 at 17:09
0
You can check for the variables type, to specify its the correct data-type that you want. The type(a)
function will return a class, and then type(a).__name__
will give you the string form.

dwb
- 2,136
- 13
- 27
0
You can check both type
and value of that variable. For example if you want to check if a == 0.0
specially you can use:
if type(a) != bool and a == 0

Binh
- 1,143
- 6
- 8
0
You could use short circuit trickery with is
:
if (a and False) is not False:
# ...
or
if not(a or a is False):
# ...

Alain T.
- 40,517
- 4
- 31
- 51