3、python布尔类型和条件表达式

使用布尔值进行分支逻辑!

文章目录

  • 1.布尔类型
    • 1.1比较运算
    • 1.2组合布尔值
  • 2.条件语句
    • 2.1布尔转换

1.布尔类型

Python有一种称为bool的变量类型。它有两个可能的值:TrueFalse

In [1]:

x = True
print(x)
print(type(x))
True
<class 'bool'>

除了直接在代码中使用TrueFalse之外,我们通常通过布尔运算符获取布尔值。这些运算符用于回答是/否问题。让我们来看一些这些运算符。

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]:

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? 

你可能感兴趣的:(从零开始的Python之旅,python)