布尔数据类型存储的是值 True
或 False
,通常分别表示为 1
或 0
。
通常有 6 个比较运算符会获得布尔
值:
符号使用情况 | 布尔型 | 运算符 |
---|---|---|
5 < 3 | False | 小于 |
5 > 3 | True | 大于 |
3 <= 3 | True | 小于或等于 |
3 >= 5 | False | 大于或等于 |
3 == 5 | False | 等于 |
3 != 5 | True | 不等于 |
你需要熟悉三个逻辑运算符:
逻辑使用情况 | 布尔型 | 运算符 |
---|---|---|
5 < 3 and 5 == 5 |
False | and - 检查提供的所有语句是否都为 True |
5 < 3 or 5 == 5 |
True | or - 检查是否至少有一个语句为 True |
not 5 < 3 |
True | not - 翻转布尔值 |
要详细了解 George Bool 如何改变了这个世界,请参阅这篇文章!
请在这道练习中尝试比较运算符!这段代码会计算里约和旧金山的人口密度。
请编写代码来比较这两个密度。旧金山的人口密度比里约的高吗?如果高,则输出 True
,否则输出 False
。
sf_population, sf_area = 864816, 231.89
rio_population, rio_area = 6453682, 486.5
san_francisco_pop_density = sf_population/sf_area
rio_de_janeiro_pop_density = rio_population/rio_area
# Write code that prints True if San Francisco is denser than Rio, and False otherwise
is_denser = san_francisco_pop_density > rio_de_janeiro_pop_density
print(is_denser)
为何 Python 使用 ==
检查是否相等,而不是 =
?