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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset