0

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?

3
  • related: stackoverflow.com/questions/27431249/python-false-vs-0 not a duplicate though because of the float issue Commented 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. Commented 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. Commented Apr 16, 2020 at 16:40

4 Answers 4

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

Note that a == 0 and a is not False can be chained with 0 == a is not False.
@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.
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.

Comments

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 

Comments

0

You could use short circuit trickery with is:

if (a and False) is not False: # ... 

or

if not(a or a is False): # ... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.