How to check logical value of an expression in the interactive shell?

378 views Asked by At

Sometimes I want to check the logical value of an expression, so I type it in Python (or IPython) and get the result:

>>> a==3
True

But in other cases it doesn't work that way (here string is None):

>>> string
>>>

So I check the logical value like this:

>>> if string: print('True')
...
>>>

Is there a shorter way for checking the logical value of an expression? Any function that returns True or False the same way it will be evaluated in an if-condition?

4

There are 4 answers

0
Eugene Yarmash On BEST ANSWER

Is there a shorter way for checking the logical value of an expression?

Yes, it's the bool() function:

>>> string = None
>>> bool(string)
False
0
Martijn Pieters On

All expressions except those that produce None are echoed.

If you execute an expression that doesn't result in data being echoed, then you probably have a None result. You can test for None explicitly:

>>> string = None
>>> string is None
True

Using is None produces a non-None result.

If you just wanted to test for the boolean value of an expression, use the bool() function; it'll return a result following the standard truth value testing rules:

>>> string = None
>>> bool(string)
False

Again, this is guaranteed to not be None and echoed. You can't distinguish between None and other false-y values this way, however. An empty string '' will also result in False, for example.

Another alternative is to explicitly print all expression results, using the repr() function:

>>> print(repr(string))
None

This then produces the exact same output as echoing does, with the single exception that None is printed too.

0
lxop On

Yes, create a boolean directly from the expression, which will always be True or False:

>>> bool(string)
False
8
magicleon94 On

string is None or string is not None will return the boolean you need.

>>> string = None
>>> string is None
>>> True