Python 中,and 和 or 运算符的运算规则

一、and 运算符

如果第一个操作数为‌假值‌(falsy),则返回该操作数,不再计算第二个操作数。

如果第一个操作数为‌真值‌(truthy),则返回第二个操作数。

python 复制代码
print(0 and 1)       # 输出: 0
print(False and 1)   # 输出: False
print(-1 and 1)      # 输出: 1

二、or 运算符

如果第一个操作数为‌真值‌(truthy),则返回该操作数,不再计算第二个操作数。

如果第一个操作数为‌假值‌(falsy),则返回第二个操作数。

python 复制代码
print(1 or 0)        # 输出: 1
print(True or 0)     # 输出: True
print(-1 or 0)       # 输出: -1

三、if中的and运算符 返回结果

题目:if(6<9 and 10) 的条件判断结果为 True

解析:

  1. (6<9 and 10)也就是and 运算符会返回 10,虽然 10 在布尔上下文中被视为真值,但 and 运算符本身返回的是实际的值 10 ,而不是转换为布尔值 True
  2. 只是if(6<9 and 10) 的条件判断结果为 True条件为真,返回执行相应的代码块

四、总结

这种行为称为"短路求值"(short-circuit evaluation),即一旦结果可以确定,就不会再计算后续表达式。

相关推荐
gf13211112 小时前
【python_使用指定应用发送飞书卡片】
java·python·飞书
Dxy12393102162 小时前
Python转Word为PDF:办公自动化的高效利器
python·pdf·word
Thomas.Sir2 小时前
第十章:RAG知识库开发之【LangSmith 从入门到精通:构建生产级 LLM 应用的全链路可观测性平台】
人工智能·python·langsmith·langchian
初心未改HD2 小时前
从Java转行大模型应用,Agent应用开发,Function Calling学习
人工智能·python
tigerlib2 小时前
vscode python环境调试,不能调到环境内部,怎么解决
ide·vscode·python
今天又在摸鱼2 小时前
py工程+爬虫
开发语言·python
李松桃2 小时前
Python爬虫-第一课
开发语言·python
清水白石0082 小时前
Python 项目 CI/CD 信心模型:证据驱动部署,从“勇敢上线”到“零风险发版”实战指南
驱动开发·python·ci/cd
在放️2 小时前
Python 爬虫 · 理论基础
开发语言·爬虫·python