使用布尔值进行分支逻辑!
1.布尔类型
Python有一种称为bool
的变量类型。它有两个可能的值:True
和False
。
In [1]:
x = True
print(x)
print(type(x))
True
<class 'bool'>
除了直接在代码中使用True
或False
之外,我们通常通过布尔运算符获取布尔值。这些运算符用于回答是/否问题。让我们来看一些这些运算符。文章来源:https://www.toymoban.com/news/detail-798684.html
1.1比较运算
Operation | Description | Operation | Description | |
---|---|---|---|---|
a == b |
a equal to b
|
a != b |
a not equal to b
|
|
a < b |
a less than b
|
a > b |
a greater than b
|
|
a <= b |
a less than or equal to b
|
a >= b |
a greater than or equal to b
|
In [2]:文章来源地址https://www.toymoban.com/news/detail-798684.html
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?"""
# The US Constitution says you must be at least 35 years old
return age >= 35
print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))
Can a 19-year-old run for president? False
Can a 45-year-old run for president?
到了这里,关于3、python布尔类型和条件表达式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!