在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
相关推荐
孟健7 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞9 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽11 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程16 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪16 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook16 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python