In Python, variables have truthy values based on their content. For example:
>>> def a(x):
... if x:
... print (True)
...
>>> a('')
>>> a(0)
>>> a('a')
True
>>>
>>> a([])
>>> a([1])
True
>>> a([None])
True
>>> a([0])
True
I also know I can print the truthy value of a comparison without the if operator at all:
>>> print (1==1)
True
>>> print (1<5)
True
>>> print (5<1)
False
But how can I print the True
/ False
value of a variable? Currently, I'm doing this:
print (not not a)
but that looks a little inelegant. Is there a preferred way?
Use the builtin bool
type.
print(bool(a))
Some examples from the REPL:
>>> print(bool(''))
False
>>> print(bool('a'))
True
>>> print(bool([]))
False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.