Python逻辑运算符详解

Python 中的逻辑运算符用于对布尔值(True/False)进行逻辑运算,也可用于表达式的组合。主要有三个:and、or 和 not。

1. 基本用法

运算符 描述 示例
and 逻辑与:两边都为 True 时结果为 True True and False → False
or 逻辑或:至少一边为 True 时结果为 True True or False → True
not 逻辑非:取反 not True → False

2. 短路求值

  • and:如果左边表达式为 False,右边将不会执行,直接返回 False。
  • or:如果左边表达式为 True,右边将不会执行,直接返回 True。

这可以用于避免无效操作,例如:

python

复制代码
x = 10
复制代码
if x > 0 and 100 / x > 5:
复制代码
    print("ok")   #安全,因为x\>0为True时才计算除法

3. 返回值

逻辑运算符不一定返回 True/False,而是返回决定最终结果的那个操作数的值

  • and:如果左边为假,返回左边;否则返回右边。
  • or:如果左边为真,返回左边;否则返回右边。
  • not:总是返回 True 或 False。

python

复制代码
print(3 and 5)      # 5 (3为真,返回5)
复制代码
print(0 and 5)      # 0 (0为假,返回0)
复制代码
print(3 or 5)       # 3 (3为真,返回3)
复制代码
print(0 or 5)       # 5 (0为假,返回5)
复制代码
print(not 3)        # False
复制代码
print(not 0)        # True

利用此特性可以简化代码:

python

复制代码
name = input("输入姓名: ") or "匿名"
复制代码
print(name)   #如果用户直接回车(空字符串),name变为"匿名"

4. 优先级

优先级从高到低:not > and > or。可以使用括号改变优先级。

相关推荐
金銀銅鐵9 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1114 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0016 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵18 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf19 小时前
Agent 流程编排
后端·python·agent
copyer_xyf19 小时前
Agent RAG
后端·python·agent
copyer_xyf19 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf19 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python