Python 简明教程
Python - Booleans
Python Booleans (bool)
在 Python 中, bool 是 int type 的子类型。bool 对象有两种可能的值,且由 Python 关键字 True 和 False 初始化。
In Python, bool is a sub-type of int type. A bool object has two possible values, and it is initialized with Python keywords, True and False.
Example
>>> a=True
>>> b=False
>>> type(a), type(b)
(<class 'bool'>, <class 'bool'>)
bool 对象被接受为 type conversion 函数的参数。对于 True 参数,int() 函数将返回 1,float() 将返回 1.0;而对于 False,它们将分别返回 0 和 0.0。我们有一个 complex() 函数的一元参数版本。
A bool object is accepted as argument to type conversion functions. With True as argument, the int() function returns 1, float() returns 1.0; whereas for False, they return 0 and 0.0 respectively. We have a one argument version of complex() function.
如果参数是复杂的,则将其作为实部,将其虚部系数设置为 0。
If the argument is a complex object, it is taken as real part, setting the imaginary coefficient to 0.
Python Boolean Expression
Python 布尔表达式是求值为布尔值表达式的表达式。它几乎总涉及 comparison operator 。在以下示例中我们将了解比较运算符如何为我们提供布尔值。bool() 方法用于返回表达式的真值。
Python boolean expression is an expression that evaluates to a Boolean value. It almost always involves a comparison operator. In the below example we will see how the comparison operators can give us the Boolean values. The bool() method is used to return the truth value of an expresison.
Syntax: bool([x])
Returns True if X evaluates to true else false.
Without parameters it returns false.
下面我们有使用数字流和布尔值作为 bool 函数的参数的示例。结果会根据参数显示真或假。
Below we have examples which use numbers streams and Boolean values as parameters to the bool function. The results come out as true or false depending on the parameter.
Example
# Check true
a = True
print(bool(a))
# Check false
a = False
print(bool(a))
# Check 0
a = 0.0
print(bool(a))
# Check 1
a = 1.0
print(bool(a))
# Check Equality
a = 5
b = 10
print(bool( a==b))
# Check None
a = None
print(bool(a))
# Check an empty sequence
a = ()
print(bool(a))
# Check an emtpty mapping
a = {}
print(bool(a))
# Check a non empty string
a = 'Tutorialspoint'
print(bool(a))