- The Python Apprentice
- Robert Smallshire Austin Bingham
- 245字
- 2021-07-02 22:16:54
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.
- Android項目開發(fā)入門教程
- Developing Mobile Web ArcGIS Applications
- 零基礎(chǔ)學(xué)Java程序設(shè)計
- Python編程實戰(zhàn)
- 微信小程序項目開發(fā)實戰(zhàn)
- Python編程:從入門到實踐
- Oracle 18c 必須掌握的新特性:管理與實戰(zhàn)
- Learning R for Geospatial Analysis
- Java程序設(shè)計案例教程
- ASP.NET程序開發(fā)范例寶典
- Learning Grunt
- 程序員的成長課
- Continuous Integration,Delivery,and Deployment
- Learning IBM Bluemix
- 交互設(shè)計語言:與萬物對話的藝術(shù)(全兩冊)