NOTE基于 Python 3。
条件:if / elif / else
score = 85if score >= 90: grade = "A"elif score >= 80: grade = "B"elif score >= 60: grade = "C"else: grade = "F"print(grade)elif 可以没有或有多个,else 可有可无。空分支写 pass。
None、False、0、''、[]、{} 在条件里当假,其余一般为真。Truth Value Testing
if / for / while 中赋值的变量在代码块外仍然可以使用。函数具有独立的局部作用域。
比较与链式比较
比较运算符:== != < <= > >=,以及 is / is not(身份)、in / not in(成员)。可链式写:a < b <= c 等价于 a < b and b <= c,且 b 只算一次(Comparisons)。
三元表达式(条件表达式)
语法:value_if_true if condition else value_if_false。先计算 condition,再选择其中一个表达式:
status = "adult" if age >= 18 else "minor":= 可在表达式中赋值(PEP 572):
words = ["a", "b", "c", "d"]if (n := len(words)) > 3: print(n)循环:while 与 for
while
条件为 True 时重复执行循环体。
n = 3while n > 0: print(n) n -= 1print("lift off")for
for 语句 依次取出元素赋给循环变量。列表、字符串、range 都可以。
words = ["Python", "is", "great"]for w in words: print(w)遍历 dict 时,默认迭代键;要键值用 .items()。
break、continue
break— 立刻跳出最内层 enclosing 循环。continue— 跳过本次剩余 suite,进入下一轮迭代。
for x in range(10): if x % 2 == 0: continue if x > 5: break print(x) # 1, 3, 5循环的 else 子句
while / for 可以带 else:循环正常结束(没有被 break 中断)时执行 else 子句。
for n in [2, 4, 6, 8]: if n % 2 == 1: print("found odd") breakelse: print("all even")match / case(3.10+)
3.10 起可用 match / case 按值分支(PEP 636)。3.9 及更早没有这套语法。
code = 404match code: case 200: msg = "OK" case 404: msg = "Not Found" case 500 | 502 | 503: msg = "Server Error" case _: msg = "Unknown"print(msg)_ 为通配模式。可解构序列、映射、对象属性。
range
range 是不可变整数序列,不占完整 list 内存。
range(stop) # 0 .. stop-1range(start, stop) # start .. stop-1range(start, stop, step) # step 不可为 0print(list(range(5))) # [0, 1, 2, 3, 4]print(list(range(2, 8, 2))) # [2, 4, 6]print(list(range(0, -3, -1))) # [0, -1, -2]需要 list 时再 list(range(...))。
enumerate 与 zip
enumerate(iterable, start=0) — 产出 (index, item):
for i, fruit in enumerate(["apple", "banana"], start=1): print(i, fruit)zip — 并行迭代,每次得到一组值,长度取最短:
names = ["Alice", "Bob"]scores = [90, 85]for name, score in zip(names, scores): print(name, score)长度不等时余下部分丢弃。要对齐最长一侧,用 itertools.zip_longest。
斐波那契
a, b = 0, 1while a < 1000: print(a, end=", ") a, b = b, a + bprint()固定项数可以用 for:
a, b = 0, 1for _ in range(10): print(a, end=" ") a, b = b, a + bprint()要存起来就往 list 里 append:
result = []a, b = 0, 1for _ in range(8): result.append(a) a, b = b, a + bprint(result) # [0, 1, 1, 2, 3, 5, 8, 13]列表推导式
List Comprehensions:[expression for item in iterable if condition]。
squares = [x * x for x in range(10)]evens = [x for x in range(20) if x % 2 == 0]嵌套循环从左到右等价于嵌套 for:
pairs = [(x, y) for x in range(3) for y in range(3) if x != y]简单变换用推导式;副作用多或逻辑复杂时用普通 for。
保序去重
raw = [3, 1, 2, 3, 2, 1]ordered_unique = list(dict.fromkeys(raw))print(ordered_unique) # [3, 1, 2]集合与字典推导式
集合推导式 — {expr for item in iterable if cond},花括号与 dict 字面量相同,但无冒号:
unique_lengths = {len(w) for w in ["hi", "hello", "hi"]}print(unique_lengths) # {2, 5}字典推导式 — {key: value for ...}:
word_map = {w: len(w) for w in ["Python", "Java", "Go"]}print(word_map)生成器表达式
语法与 list 推导式类似,圆括号:(expr for item in iterable if cond)。产出 iterator,惰性求值:
total = sum(x * x for x in range(1000000)) # 外层函数吞掉括号gen = (x * x for x in range(5))print(next(gen)) # 0print(list(gen)) # [1, 4, 9, 16] — 已消耗 0单独写 (x for x in iterable) 是生成器表达式;仅 {}、[] 构成 dict / list 推导式。单层 (x for ...) 与调用写成 func(x for ...) 时,圆括号可省略一层(Generator expressions)。
推导式里的海象 := 见 PEP 572。
附录:控制流与推导式语法速查
| 构造 | 语法要点 |
|---|---|
| 条件 | if / elif / else + 缩进 suite |
| 三元 | a if cond else b |
| match | match subject: + case pattern:(3.10+) |
| while | while cond: |
| for | for target in iterable: |
| break / continue | 仅作用于最内层循环 |
| 循环 else | 未 break 时执行 |
| list 推导 | [e for x in it if c] |
| set 推导 | {e for x in it if c} |
| dict 推导 | {k: v for x in it if c} |
| 生成器表达式 | (e for x in it if c) |
常用内置(循环相关)
| 名称 | 作用 |
|---|---|
range | 整数序列 |
enumerate | 带索引迭代 |
zip | 并行迭代 |
len | 长度 |
sum / min / max | 聚合(可接可迭代对象) |
sorted | 返回新排序 list |
reversed | 返回 reverse iterator |
参考
官方文档(中文版):
- More Control Flow Tools —
if、while、for、break/continue/else、匹配语句 - First Steps Towards Programming — 斐波那契
while示例 - List Comprehensions — 列表推导与集合推导
- Looping Techniques —
enumerate、zip、dict 遍历 - The for statement
- The while statement
- Generator expressions
- range — 构造与步长
- enumerate() / zip()
- Truth Value Testing
PEP:
- PEP 636 — Structural Pattern Matching —
match/case
菜鸟教程: