1

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?

MaxGyver
  • 428
  • 7
  • 21
  • you can test for None with `string is not None` which returns `False` in your example – GPhilo Sep 15 '17 at 09:06
  • I know. I want to check, if *string* returns *True* or *False* in an if-condition. But if I type *string* (the next line), I just get no result. – MaxGyver Sep 15 '17 at 09:07
  • I have removed the assignment of string from the code block, so now it's clearer what I meant. – MaxGyver Sep 15 '17 at 09:14
  • If `string` is `None` you'll always get no result, see @Martijn Pieter's answer for the reason why. There's no way around that, that's how the interpreter works. You need to explicitly test for `None` or convert it to a `bool` before printing it. – GPhilo Sep 15 '17 at 09:16

4 Answers4

7

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
5

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

Yes, it's the bool() function:

>>> string = None
>>> bool(string)
False
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
2

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

>>> bool(string)
False
lxop
  • 7,596
  • 3
  • 27
  • 42
1

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

>>> string = None
>>> string is None
>>> True
magicleon94
  • 4,887
  • 2
  • 24
  • 53