Post

Python Controlflow

流程控制

  • if
  • for
  • while

判断控制结构

Python 中的判断控制结构主要有 if-elif-elseternary operator

if-elif-else

1
2
3
4
5
6
if condition1:
    # 当条件 1 满足时执行的代码
elif condition2:
    # 当条件 1 不满足且条件 2 满足时执行的代码
else:
    # 当条件 1 和条件 2 都不满足时执行的代码

其中,condition1condition2 等都是需要判断的条件表达式,可以使用比较运算符、逻辑运算符等来组合成复杂的判断条件。当条件 condition1 满足时,执行对应的代码块;否则继续判断下一个条件 condition2 ,以此类推,直到找到一个满足条件的代码块或者所有条件都不满足时,执行最后的 else 块。

ternary operator

1
result = value1 if condition else value2

其中,condition 是需要判断的条件表达式,当条件成立时,返回 value1,否则返回 value2 。这种语法结构也称为三目运算符,简单明了,通常用于在一行代码中完成简单的条件判断。

循环结构

for

for 循环通常用于遍历序列类型(如字符串、列表、元组等)中的元素,语法结构如下:

1
2
for 变量 in 序列:
    # 循环体

其中,变量 表示接收到的序列元素,序列 是需要遍历的序列,循环会按顺序依次将序列中的元素赋值给 变量,然后执行循环体中的语句。例如:

1
2
3
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

上述代码会输出 applebananacherry 三个字符串,分别对应 fruits 列表中的三个元素。

while

while 循环会在满足条件时重复执行循环体,直到条件不再成立为止。语法结构如下:

1
2
while 条件:
    # 循环体

其中,条件 是判断条件,如果成立则进入循环体执行;否则结束循环。例如:

1
2
3
4
i = 1
while i <= 5:
    print(i)
    i += 1

上述代码会输出数字 1 到 5,因为当 i 的值小于等于 5 时,满足条件,会不断地执行循环体中的代码,每次输出 i 的值,并将 i 加 1。当 i 大于 5 时,不再满足条件,循环结束。

循环中语句

break

break语句可以在循环内部立即终止循环,并跳出循环体。

1
2
3
4
for i in range(10):
    if i == 5:
        break
    print(i)

continue

continue语句在循环中用于跳过当前迭代,并进入下一次迭代。

1
2
3
4
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

pass

pass语句在Python中是一个空语句,用于表示占位符,不做任何操作。

1
2
3
4
5
for i in range(10):
    if i == 5:
        pass
    else:
        print(i)

range() 函数

range() 函数是 Python 内置函数之一,它用于创建一个整数列表,常用于 for 循环中。 range() 函数有三个参数:起始值、终止值和步长。

  • 语法如下

    1
    
    range(start, stop[, step])
    
  • 说明

    • start:表示数列的起始值,默认为 0。
    • stop:表示数列的终止值(不包括),必须指定。
    • step:表示数列的公差,默认为 1。

返回的结果是一个可迭代对象,可以使用 list() 函数将其转换为列表

  • 例子

    1
    2
    3
    4
    5
    6
    7
    
    # 打印 0 到 4 的整数
    for i in range(5):
        print(i)
      
    # 打印 2 到 8 的偶数
    for i in range(2, 9, 2):
        print(i)
    
  • 输出:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
      0
      1
      2
      3
      4
      2
      4
      6
      8
    

需要注意的是, range() 函数返回的是一个不可变序列,在 Python 2.x 中叫做 xrange()。如果需要修改序列中的元素,可以使用其他数据类型,如列表或数组。

match 语法

match 是 Python 3.10 新增的一种模式匹配语法,也被称为结构化匹配。它提供了更加简洁和易于理解的方式来匹配和分解复杂数据结构,例如元组、列表、字典等。

  • match 的语法如下:
1
2
3
4
5
6
7
match expression:
    case pattern_1:
        # 处理 pattern_1 的情况
    case pattern_2 if condition:
        # 处理 pattern_2 和条件成立的情况
    case _:
        # 处理其他情况

其中 expression 表示要进行匹配的表达式,可以是任意类型的值,如数字、字符串、元组、列表等。 pattern 是一种匹配模式,用于匹配 expression 中的值。

case 子句用来指定不同的匹配情况,可以指定多个 case 子句,每个子句包含一个 pattern 和对应的处理逻辑。多个子句按照出现顺序进行匹配,匹配成功后执行对应的处理逻辑。

如果所有的 case 都没有匹配成功,则会执行 _ 子句中的代码块,类似于 switch-case 语句中的 default 分支。

  • match 进行模式匹配的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def match_example(x):
    match x:
        case 0:
            print("x is zero")
        case 1:
            print("x is one")
        case _ if x > 1:
            print("x is greater than one")
        case _:
            print("x is a negative number")

match_example(0)    # 输出 "x is zero"
match_example(1)    # 输出 "x is one"
match_example(2)    # 输出 "x is greater than one"
match_example(-1)   # 输出 "x is a negative number"

需要注意的是,match 语法仅在 Python 3.10 及以上版本中可用,如果使用较早的 Python 版本,则无法使用。

循环技巧

  1. 使用 range() 函数来生成一个数列,可以用于循环:
    1
    2
    
     for i in range(10):
         print(i)
    
  2. 使用 enumerate() 函数来同时遍历序列的下标和值:

    1
    2
    3
    
     fruits = ['apple', 'banana', 'cherry']
     for i, fruit in enumerate(fruits):
         print(i, fruit)
    
  3. 使用 zip() 函数来同时遍历多个序列:

    1
    2
    3
    4
    
     fruits = ['apple', 'banana', 'cherry']
     prices = [0.5, 0.25, 0.3]
     for fruit, price in zip(fruits, prices):
         print(fruit, price)
    
  4. 使用列表解析式来快速生成一个新的列表:

    1
    2
    3
    
     numbers = [1, 2, 3, 4, 5]
     squares = [x**2 for x in numbers]
     print(squares)
    
  5. 使用条件表达式(三元运算符)来简化 if-else 语句:

    1
    2
    3
    
     x = 10
     y = 'yes' if x > 5 else 'no'
     print(y)
    
This post is licensed under CC BY 4.0 by the author.