2

Let's say we have the following code which detects the stars rating of a document. If the stars rating is 50.0 it'll indicate it using stars_indicator = True and we would like to 'do something' in such case, if the stars rating is 10.0 it'll indicate it using stars_indicator = False and we would like to 'do something else' in this case.

stars_indicator = sentiment_indicator = None
if document[stars] == 50.:
   stars_indicator = True
elif document[stars] == 10.:
   stars_indicator = False

How can we check if we should 'do something' or 'do something else'?

Checking if it's True is simple

if stars_indicator:
   # do something

The trivial approach for checking if it's False or None will be

if not stars_indicator:
   # do something else

But in this way the if condition won't distinguish between the two options and will 'do something else' if stars_indicator False or None.

Lior Magen
  • 1,533
  • 2
  • 15
  • 33
  • 2
    Possible duplicate of [In Python how should I test if a variable is None, True or False](https://stackoverflow.com/questions/2020598/in-python-how-should-i-test-if-a-variable-is-none-true-or-false) – Andrew Guy Oct 02 '17 at 07:23

3 Answers3

10

A much better way is to explicitly check for False or None with is:

if stars_indicator is None:
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
1

While others have answered how to check if your variable is True, False or None, I would like to point out that in your code snippet it would probably be easier if you just work without your stars_indicator:

if document[stars] == 50.:
    # Do what you would do if stars_indicator was True
elif document[stars] == 10.:
    # Do what you would do if stars_indicator was False
else:
    # Do what you would do if stars_indicator was None

In this way you do not need to encode your results in a variable just to then having to interpret your variable again. Of course this is all based on the code snippet you provided.

NOhs
  • 2,780
  • 3
  • 25
  • 59
  • Could you clarify where I changed the logic of your code? Based on the example you provided it should still do the same without the need to distinguish between True, False or None. Of course if your real code is more complicated it might not be the preferred option, but I still think this answer is useful for people who look it up and don't realize that there might be an easier option. So I do not really understand the downvote. – NOhs Oct 02 '17 at 08:03
  • I meant to reply to a different comment, my bad. – Lior Magen Oct 02 '17 at 10:08
-1

The right approach for this kind of problem is using isinstance()

if isinstance(stars_indicator, bool) and not stars_indicator:
   # do something else

isinstance(stars_indicator, bool) will first make sure that the variable is not None and only than will make sure that it's False.

This is an issue I had and wanted to share its solution.

Lior Magen
  • 1,533
  • 2
  • 15
  • 33