惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
O
OpenAI News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
Arctic Wolf
T
Tor Project blog
G
GRAHAM CLULEY
I
InfoQ
博客园_首页
IT之家
IT之家
The Register - Security
The Register - Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
P
Proofpoint News Feed
The GitHub Blog
The GitHub Blog
Blog — PlanetScale
Blog — PlanetScale
N
Netflix TechBlog - Medium
K
Kaspersky official blog
博客园 - 三生石上(FineUI控件)
S
SegmentFault 最新的问题
U
Unit 42
PCI Perspectives
PCI Perspectives
量子位
P
Palo Alto Networks Blog
S
Securelist
T
Troy Hunt's Blog
博客园 - 【当耐特】
Recorded Future
Recorded Future
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security Affairs
Engineering at Meta
Engineering at Meta
T
The Blog of Author Tim Ferriss
博客园 - 聂微东
罗磊的独立博客
N
News and Events Feed by Topic
人人都是产品经理
人人都是产品经理
B
Blog RSS Feed
NISL@THU
NISL@THU
C
Cisco Blogs
T
Threatpost
有赞技术团队
有赞技术团队
Forbes - Security
Forbes - Security
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
T
The Exploit Database - CXSecurity.com
Cloudbric
Cloudbric
Cyberwarzone
Cyberwarzone
Google DeepMind News
Google DeepMind News
C
Cyber Attacks, Cyber Crime and Cyber Security

木灵鱼儿

从零开始:手把手教你封装一个企业级 Axios 请求模块 - 木灵鱼儿 03-Vue Query 高级进阶:应对复杂业务场景的硬核套路 - 木灵鱼儿 02-Vue Query 快速入门:从零构建你的第一个声明式查询 - 木灵鱼儿 01-异步状态管理新范式:为什么在 Vue 3 中使用 vue-query? - 木灵鱼儿 git 如何将所有历史提交合并为一条 - 木灵鱼儿 Windows 下如何快速复制目录的同时排除指定的目录和文件 - 木灵鱼儿 x86多网口软路由+pve+爱快ikuai+iStoreOS实现组网和翻墙 - 木灵鱼儿 生产部署时动态导入 Chunk 失效的实用回退方案 - 木灵鱼儿 如何在 Vite 项目中优雅地展示用户协议?(Markdown 转 Vue 组件方案) - 木灵鱼儿 Vue 路由守卫进阶:用策略模式告别 if-else - 木灵鱼儿 16 Python for循环 - 木灵鱼儿 15 Python while循环 - 木灵鱼儿 如何生成一个“扫码连WIFI”的二维码 - 木灵鱼儿 14 Python 分支语句if - 木灵鱼儿 13 Python 字符串详解 - 木灵鱼儿
12 Python 语句、表达式与运算符 - 木灵鱼儿
木灵鱼儿 · 2026-01-21 · via 木灵鱼儿

语句与表达式 (Statements vs. Expressions)

这是编程中非常核心的概念,区分它们有助于你理解代码是如何运行的。

什么是表达式 (Expression)?

表达式是“由于计算而产生值”的代码片段。 简单来说,只要你能把它放在 print() 函数里打印出来的,通常都是表达式。

  • 特点:它总会返回一个结果(值)。
  • 例子

    • 1 + 1 (计算结果为 2)
    • "Hello World" (字符串本身也是表达式)
    • len("abc") (函数调用返回 3)

什么是语句 (Statement)?

语句是“执行某种动作”的代码单位。 它像是一个指令,告诉 Python 去做某件事(比如赋值、循环、判断),而不是为了生成一个值。

  • 特点:它改变了程序的状态(例如改变变量的值),但它本身不“返回”值。
  • 例子

    • a = 10 (赋值语句)
    • if x > 0: (条件语句)
    • import math (导入语句)

代码对比

# --- 表达式 (Expressions) ---
# 它们都有“值”,可以直接打印
print(3 + 5)        # 8
print("Py" + "thon") # Python

# --- 语句 (Statements) ---
x = 10  # 这是一个赋值语句。
# print(x = 10)  # 报错!因为赋值语句本身没有返回值,不能被打印。

# 特例:Python 3.8+ 引入了海象运算符 (:=),让赋值也能成为表达式
if (n := len("test")) > 3:
    print(f"长度是 {n}") # 这里 n := ... 既赋值了又返回了值

计算/算术运算符 (Arithmetic Operators)

用于执行常见的数学运算。Python 的数学运算非常符合直觉。

运算符描述示例结果
+加法5 + 38
-减法5 - 32
*乘法5 * 315
/除法 (总是返回浮点数)10 / 25.0
//整除 (向下取整)10 // 33
%取模 (求余数)10 % 31
**幂运算 (次方)2 ** 38

代码示例

a = 10
b = 3

print(f"{a} 除以 {b} 等于: {a / b}")       # 3.3333...
print(f"{a} 整除 {b} 等于: {a // b}")      # 3 (去掉小数部分)
print(f"{a} 对 {b} 取余 等于: {a % b}")    # 1 (10 - 3*3 = 1)
print(f"2 的 3 次方: {2 ** 3}")           # 8

# 小技巧:利用 % 判断奇偶
num = 7
if num % 2 == 0:
    print("偶数")
else:
    print("奇数") # 输出这个

比较运算符 (Comparison Operators)

用于比较两个值,结果永远是布尔值 (TrueFalse)。

运算符描述示例
==等于 (注意是两个等号)5 == 5 (True)
!=不等于5 != 3 (True)
>大于5 > 3 (True)
<小于5 < 3 (False)
>=大于等于5 >= 5 (True)
<=小于等于4 <= 5 (True)

代码示例

score = 85
pass_mark = 60

is_passed = score >= pass_mark  # 这是一个表达式,计算结果赋值给变量
print(f"是否及格: {is_passed}") # True

# Python 独有的连写比较
x = 5
# 判断 x 是否在 1 到 10 之间
print(1 < x < 10)  # True (相当于 1 < x and x < 10)

赋值运算符 (Assignment Operators)

除了基本的赋值 =,Python 还提供了复合赋值运算符,用于简化代码(Syntactic Sugar)。

运算符等价于示例
=赋值c = a + b
+=c = c + ac += a
-=c = c - ac -= a
*=c = c * ac *= a
/=c = c / ac /= a

代码示例

count = 0

# 传统写法
count = count + 1

# 推荐写法 (更简洁)
count += 1
print(count) # 2

price = 100
price *= 0.8 # 打八折
print(price) # 80.0

逻辑运算符 (Logical Operators)

用于组合多个条件,结果也是布尔值。

运算符描述逻辑
and只有两边都为 True,结果才为 True
or只要有一边为 True,结果就为 True
not取反,TrueFalse,反之亦然

关键概念:短路运算 (Short-circuit Evaluation)

Python 比较“懒”,如果看完左边就能确定结果,它就不会去计算右边。

  • A and B: 如果 A 是 False,结果必为 False,Python 不会去计算 B。
  • A or B: 如果 A 是 True,结果必为 True,Python 不会去计算 B。

代码示例

age = 25
has_ticket = True

# and 演示
if age >= 18 and has_ticket:
    print("允许进入")

# not 演示
is_raining = False
if not is_raining:
    print("天气不错,出去玩吧")

# 短路演示
def risky_function():
    print("我被运行了!")
    return True

# 因为 True or ... 结果已经是 True,所以 risky_function 不会被执行
if True or risky_function():
    print("短路测试结束")
# 输出结果中不会出现 "我被运行了!"

成员运算符 (Membership Operators)

用来测试一个序列(如列表、字符串、元组)中是否包含指定的项。这让代码读起来非常像英语。

运算符描述
in如果在序列中找到值,返回 True
not in如果在序列中没有找到值,返回 True

代码示例

# 1. 在列表中查找
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
    print("我想吃香蕉")

# 2. 在字符串中查找
message = "Error: File not found"
if "Error" in message:
    print("出现错误!")

# 3. 在字典中查找 (默认查找 Key)
user = {"name": "Jack", "age": 20}
if "name" in user:
    print("用户有名字属性")

运算符优先级 (Operator Precedence)

当一个表达式中包含多个运算符时,Python 按照什么顺序计算?这就涉及到了优先级。

基本原则 (由高到低)

  1. () 括号 (最高优先级,想先算谁就括谁)
  2. ** 幂运算
  3. * / // % 乘除类
  4. + - 加减类
  5. > < == 比较类
  6. not
  7. and
  8. or (逻辑运算通常最低)

代码示例

# 案例 1: 乘法优先于加法
result = 2 + 3 * 4
print(result) # 14 (先算 3*4=12,再加 2)

# 案例 2: 使用括号改变顺序
result = (2 + 3) * 4
print(result) # 20

# 案例 3: 逻辑运算优先级 (not > and > or)
# 相当于: True or (True and False) -> True or False -> True
print(True or True and False) # True

建议:虽然有优先级规则,但在写复杂表达式时,最好使用括号 () 来明确你的意图。这样不仅避免出错,也让代码更容易被别人(和你自己)读懂。

版权申明

本文系作者 @木灵鱼儿 原创发布在木灵鱼儿站点。未经许可,禁止转载。