在python中使用布尔逻辑

布尔是python中常见类型。它的值只能是两项内容之一:true或false.

编写"if"语句

若要在python中表达条件逻辑,可以使用if语句。------编写If语句离不开逻辑运算符:等于、不等于、小于、大于或等于、大于和大于或等于。

在python中的表示方法:

等于:a==b

不等于:a != b

小于:a < b

小于或等于:a <= b

大于:a > b

大于或等于:a >= b

测试表达式:

只有满足特定条件时,才能够运行执行代码块。即测试表达式为True,则运行下一个缩进代码块:

python 复制代码
a = 97
b = 55
if a < b:
    print(b)

由此我们可以得到,if语句的语法始终为:

python 复制代码
if test_expression:
    # statement(s) to be run

注:在python中,if语句的主体必须缩进。测试表达式后面没有缩进的任何代码都将始终运行

那这是测试条件为True的情况,如果为False呢?

------"else"和"elif"语句

当测试结果为False时,可以使用"else"和"elif"语句来执行更多的代码块,在不同测试条件下

使用else

python 复制代码
a = 27
b = 93
if a >= b:
    print(a)
else:
    print(b)

语法格式:

python 复制代码
if test_expression:
    # statement(s) to be run
else:
    # statment(s) to be run

使用elif

在Python中,关键字elif是"否则如果"的缩写。使用elif语句可以将多个测试表达式添加到程序中。这些语句按照其编写顺序运行,因此只有当第一个if语句为False时,程序才会输入elif语句

python 复制代码
a = 27
b = 93
if a <= b:
    print("a is less than or equal to b")
elif a == b:
    print("a is equal to b")

结合使用if,elif和else语句

可以结合使用if、elif和else语句来创建具有复杂逻辑的程序。------仅当if条件为false时才运行elif语句。另请注意,一个if块只能有一个else块,但它可以有多个elif块。

具体语法:

python 复制代码
if test_expression:
    # statement(s) to be run
elif test_expression:
    # statement(s) to be run
elif test_expression:
    # statement(s) to be run
else:
    # statement(s) to be run

使用嵌套条件逻辑

Python还支持嵌套条件逻辑。若要嵌套条件,请缩进内部条件,同一缩进级别的所有内容都将在同一代码块中运行:

python 复制代码
a = 16
b = 25
c = 27
if a > b:
    if b > c:
        print ("a is greater than b and b is greater than c")
    else: 
        print ("a is greater than b and less than c")
elif a == b:
    print ("a is equal to b")
else:
    print ("a is less than b")

具体语法格式:

python 复制代码
if test_expression:
    # statement(s) to be run
    if test_expression:
        # statement(s) to be run
    else: 
        # statement(s) to be run
elif test_expression:
    # statement(s) to be run
    if test_expression:
        # statement(s) to be run
    else: 
        # statement(s) to be run
else:
    # statement(s) to be run
相关推荐
荣码34 分钟前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵11 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li13 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸18 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学19 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry