【Python3.13】官网学习之控制流

image1

if

if语句是最常见的控制流:

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...     x = 0
...     print('Negative changed to zero')
... elif x == 0:
...     print('Zero')
... elif x == 1:
...     print('Single')
... else:
...     print('More')
...
More

for

for语句用来遍历:

## Create a sample collection
users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}

## Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

## Strategy:  Create a new collection
active_users = {}
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

range

range函数生成数字序列:

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
>>> sum(range(4))  # 0 + 1 + 2 + 3
6

值得注意的是,range函数的返回类型并不是list类型,而是range对象<class 'range'>

虽然它看起来像列表,但实际上它是一个更高效的内存对象,只在需要时生成序列中的数字。例如:

  • range(5) 返回 range(0, 5)

  • type(range(5)) 返回<class 'range'>

如果需要列表,可以使用list()函数进行转换:list(range(5))会返回[0, 1, 2, 3, 4]。

break和continue

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(f"{n} equals {x} * {n//x}")
...             break
...
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
9 equals 3 * 3
>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print(f"Found an even number {num}")
...         continue
...     print(f"Found an odd number {num}")
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

else

这里的else不是if的else,而是在for循环或者while循环中的else:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # loop fell through without finding a factor
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

在for循环中,循环结束时,会执行else。在while循环中,循环条件变为false后,会执行else。比如执行了break就不会执行else,没有执行break就会执行else。

pass

pass什么都不做,可以在写代码时临时占个位置:

class MyEmptyClass:
    pass
def initlog(*args):
    pass   # Remember to implement this!

match

match语句跟C、Java的switch语句有点像,跟Rust、Haskell的模型匹配有点像。

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

注意最后一个case的_是通配符,能匹配任何值。

多个值可以用或:

case 401 | 403 | 404:
    return "Not allowed"

也能匹配元组并解包:

## point is an (x, y) tuple
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y):
        print(f"X={x}, Y={y}")
    case _:
        raise ValueError("Not a point")

还能匹配类对象:

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def where_is(point):
    match point:
        case Point(x=0, y=0):
            print("Origin")
        case Point(x=0, y=y):
            print(f"Y={y}")
        case Point(x=x, y=0):
            print(f"X={x}")
        case Point():
            print("Somewhere else")
        case _:
            print("Not a point")

可以通过设置类的__match_args__特殊属性来定义模式匹配时的位置参数顺序。例如:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
    __match_args__ = ("x", "y")  # 定义模式匹配时的参数顺序

## 以下三种模式匹配方式是等价的:
point = Point(1, 2)

match point:
    case Point(1, var):  # 使用位置参数
        print(f"y is {var}")
    case Point(x=1, y=var):  # 使用关键字参数
        print(f"y is {var}")
    case Point(y=var, x=1):  # 使用关键字参数
        print(f"y is {var}")
    case Point(1, y=var):  # 混合使用
        print(f"y is {var}")

当设置了__match_args__后,模式匹配会按照指定的顺序(x, y)来解析位置参数。这在处理复杂数据结构时能提供更灵活的模式匹配方式。

case还能加if:

match point:
    case Point(x, y) if x == y:
        print(f"Y=X at {x}")
    case Point(x, y):
        print(f"Not on the diagonal")

元组和列表模式可以匹配任意序列(除了迭代器和字符串),这与解包赋值的行为一致。示例:

def check_sequence(seq):
    match seq:
        case [1, 2, *rest]:  # 匹配任何以1,2开头的序列(除迭代器和字符串)
            print(f"匹配列表/元组,剩余元素: {rest}")
        case (1, 2, *rest):   # 与列表模式效果相同
            print(f"匹配元组/列表,剩余元素: {rest}")
        case _:
            print("不匹配")

check_sequence([1, 2, 3, 4])    # 匹配
check_sequence((1, 2, 5, 6))    # 匹配
check_sequence(range(1, 100))   # 不匹配(迭代器)
check_sequence("1234")          # 不匹配(字符串)

enum的match:

from enum import Enum
class Color(Enum):
    RED = 'red'
    GREEN = 'green'
    BLUE = 'blue'

color = Color(input("Enter your choice of 'red', 'blue' or 'green': "))

match color:
    case Color.RED:
        print("I see red!")
    case Color.GREEN:
        print("Grass is green")
    case Color.BLUE:
        print("I'm feeling the blues :(")

补充下,使用Enum枚举类相比直接定义类变量有以下主要优势:

  1. 类型安全:Enum成员是单例的,确保不会创建重复值,而类变量可以被随意修改

  2. 防止值冲突:Enum会自动处理重复值问题,比如:

    class Color(Enum):
       RED = 1
       CRIMSON = 1  # 会被视为RED的别名
    
  3. 迭代支持:Enum类可以直接迭代所有成员

    for color in Color:
       print(color)
    
  4. 值验证:Enum会自动验证值的唯一性,防止意外覆盖

  5. 功能扩展:Enum提供了额外方法如:

    • Color.RED.name 获取成员名称

    • Color.RED.value 获取成员值

    • Color['RED'] 通过名称访问成员

  6. 语义明确:明确表达了这是一组有限的、预定义的常量集合

  7. 防止实例化:Enum类不能被实例化,保证了常量使用的正确性

函数

关于函数,已经在Python入门系列和进阶系列文章介绍了,这里摘取一些官网有意思的点。

、函数如果没有return语句,实际上也会返回None:

>>> fib(0)
>>> print(fib(0))
None

而对于迭代器来说,迭代器协议要求迭代器必须实现__iter__()__next__()方法。当迭代器耗尽时,next()方法会抛出StopIteration异常,而不是返回None。这是迭代器与普通函数返回值的一个重要区别。

比如:

def my_range(n):
    i = 0
    while i < n:
        yield i
        i += 1
for num in my_range(3):
    print(num)  # 输出0,1,2
gen = my_range(3)
print(next(gen))  # 0
print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 抛出StopIteration异常,而不是返回None

这与普通函数返回None的行为形成对比,展示了Python中不同的控制流机制。

、默认参数值在函数定义时只被求值一次。当默认参数是可变对象(如列表、字典或类实例)时,这个特性会导致默认参数在多次函数调用间共享状态。比如:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

输出:

[1]
[1, 2]
[1, 2, 3]

如果不想共享状态,可以这样写:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

、函数参数可以是positional-only或keyword-only:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

示例:

def standard_arg(arg):
    print(arg)

def pos_only_arg(arg, /):
    print(arg)

def kwd_only_arg(*, arg):
    print(arg)

def combined_example(pos_only, /, standard, *, kwd_only):
    print(pos_only, standard, kwd_only)