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.
A much better way is to explicitly check for False or None with is:
if stars_indicator is None:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With