官术网_书友最值得收藏!

bool

The bool type represents logical states and plays an important role in several of Python's control flow structures, as we'll see shortly. As you would expect there are two bool values, True and False, both spelled with initial capitals:

>>> True
True
>>> False
False

There is also a bool constructor which can be used to convert from other types to bool. Let's look at how it works. For ints, zero is considered falsey and all other values truthy:

>>> bool(0)
False
>>> bool(42)
True
>>> bool(-1)
True

We see the same behavior with floats where only zero is considered falsey:

>>> bool(0.0)
False
>>> bool(0.207)
True
>>> bool(-1.117)
True
>>> bool(float("NaN"))
True

When converting from collections, such as strings or lists, only empty collections are treated as falsey. When converting from lists — which we'll look at shortly — we see that only the empty list (shown here in it's literal form of []) evaluates to False:

>>> bool([])
False
>>> bool([1, 5, 9])
True

Similarly, with strings only the empty string, "", evaluates to False when
passed to bool:

>>> bool("")
False
>>> bool("Spam")
True

In particular, you cannot use the bool constructor to convert from string representations of True and False:

>>> bool("False")
True

Since the string False is not empty, it will evaluate to True. These conversions to bool are important because they are widely used in Python
if-statements and while-loops which accept bool values in their condition.

主站蜘蛛池模板: 台山市| 洛川县| 滕州市| 松阳县| 井研县| 柯坪县| 侯马市| 南召县| 越西县| 淮南市| 福鼎市| 简阳市| 延长县| 商南县| 齐齐哈尔市| 政和县| 新泰市| 仁化县| 叙永县| 榆社县| 北宁市| 高邮市| 洛宁县| 时尚| 安西县| 商城县| 南安市| 无锡市| 仪陇县| 吴桥县| 泸溪县| 朝阳市| 涟源市| 长阳| 漳浦县| 普宁市| 龙胜| 梅河口市| 黑水县| 敦煌市| 兰州市|