在 Python 中,变量根据其内容具有真值。例如:
>>> def a(x):
... if x:
... print (True)
...
>>> a('')
>>> a(0)
>>> a('a')
True
>>>
>>> a([])
>>> a([1])
True
>>> a([None])
True
>>> a([0])
True
我也知道我可以在根本不使用 if 运算符的情况下打印比较的真值:
>>> print (1==1)
True
>>> print (1<5)
True
>>> print (5<1)
False
但是如何打印变量的 True
/False
值?目前,我正在这样做:
print (not not a)
但这看起来有点不雅。有首选方法吗?
最佳答案
使用内置的 bool
类型。
print(bool(a))
REPL 中的一些示例:
>>> print(bool(''))
False
>>> print(bool('a'))
True
>>> print(bool([]))
False
关于python - 如何打印变量的真值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39604780/