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

发布时间:2024年01月16日

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

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? 
文章来源:https://blog.csdn.net/jiangxinufo00/article/details/135600639
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。