如何打印变量的真值? [英] How can I print the Truth value of a variable?

查看:88
本文介绍了如何打印变量的真值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,变量根据其内容具有真实值.例如:

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

我也知道我可以完全不用if运算符打印比较的真实值:

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

但是如何打印变量的True/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?

推荐答案

使用内置的bool类型.

print(bool(a))

REPL中的一些示例:

Some examples from the REPL:

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

这篇关于如何打印变量的真值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆