Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to figure if a variable is None, False or True while distinguishing between None and False

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.

like image 281
Lior Magen Avatar asked Dec 12 '25 14:12

Lior Magen


2 Answers

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

if stars_indicator is None:
like image 174
Daniel Roseman Avatar answered Dec 14 '25 02:12

Daniel Roseman


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.

like image 31
NOhs Avatar answered Dec 14 '25 04:12

NOhs