How can I print the Truth value of a variable?

眉间皱痕 提交于 2019-12-12 13:09:17

问题


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?


回答1:


Use the builtin bool type.

print(bool(a))

Some examples from the REPL:

>>> print(bool(''))
False
>>> print(bool('a'))
True
>>> print(bool([]))
False


来源:https://stackoverflow.com/questions/39604780/how-can-i-print-the-truth-value-of-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!