使用布尔值进行分支逻辑!
Python有一种称为bool
的变量类型。它有两个可能的值:True
和False
。
In [1]:
x = True
print(x)
print(type(x))
True
<class 'bool'>
除了直接在代码中使用True
或False
之外,我们通常通过布尔运算符获取布尔值。这些运算符用于回答是/否问题。让我们来看一些这些运算符。
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]:
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?