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?
- related: stackoverflow.com/questions/27431249/python-false-vs-0 not a duplicate though because of the float issueTomerikoo– Tomerikoo2020-04-16 16:29:44 +00:00Commented Apr 16, 2020 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– Karl Knechtel2020-04-16 16:38:35 +00:00Commented Apr 16, 2020 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– hoffee2020-04-16 16:40:14 +00:00Commented Apr 16, 2020 at 16:40
Add a comment |
4 Answers
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') 2 Comments
blhsing
Note that
a == 0 and a is not False can be chained with 0 == a is not False.Óscar López
@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.