Question

Consider a simple if/else block in Python like the one below:

if x:
    print 'True'
else:
    print 'False'

Where x could be a comparison, a condition or simply a string/list/object. How can I open a python shell and find out what if x would evaluate to without writing the loop? i.e. is x True or False for a certain corner case value.

For example, if x is an empty list. Can I open python shell, assign x = [] and then write print <function of x> that'll output True or False on execution. What is that <function of x>?

I feel I'm asking a rather silly question and can't think straight right now but I often find myself opening a shell, assign a corner case value to a variable and write an if/else to see what corner values would evaluate to True/False. I'm just looking for a shorter way to find out on the shell, without writing the 4-line loop.

Was it helpful?

Solution

You are looking for the function bool.

>>> bool([])
False   
>>> bool(['monty'])
True

What the Python Docs say.

Convert a value to a Boolean, using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True. bool is also a class, which is a subclass of int. Class bool cannot be subclassed further. Its only instances are False and True.

OTHER TIPS

Your four lines should be the same as

print(bool(x))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top