Python 中的控制流

Python 中的控制流

本文解释了 Python 中的控制流。

YouTube Video

Python 中的 if 语句

Python 中的 if 语句是一种条件分支的语法。如果特定条件的计算结果为 True(真),它将执行一段代码块。

基本语法

Python 中的 if 语句通常遵循以下结构。

1x = 10
2
3if x > 5: # Check if the condition(x > 5) is True
4    # If the condition is True, execute this code block
5    print("x is greater than 5")

在此示例中,如果变量 x 大于 5,将打印 "x is greater than 5"

else 语句

if 语句后使用 else,可以指定在条件为假时执行的代码。

1x = 3
2
3if x > 5:
4    print("x is greater than 5")
5else:
6    print("x is less than or equal to 5")

在此示例中,输出将是 "x is less than or equal to 5"

elif 语句

如果需要检查多个条件,可以使用 elif,它代表 "else if" 的缩写。

1x = 5
2
3if x > 5:
4    print("x is greater than 5")
5elif x == 5:
6    print("x is equal to 5")
7else:
8    print("x is less than 5")

在此示例中,将打印 "x is equal to 5"

注意

  • ifelifelse 之后需要一个冒号 (:)。
  • 当条件为真时执行的代码块需要缩进。在 Python 中,标准缩进通常是 4 个空格,但其他数量的空格也可以,只要你保持一致即可。
  • 您可以使用任何计算结果为布尔值的表达式作为条件。这意味着您可以使用结合比较运算符或逻辑运算符的条件表达式。

掌握 Python 的 if 语句可以让您灵活地控制程序执行流程。

Python 中的多条件分支

在 Python 中,有几种方法可以实现类似其他语言中 switch 功能的结构。在 Python 中,通常使用 if-elif-else 语句或字典来创建类似于 switch 语句的结构。

方法 1:if-elif-else 语句

最简单的方法是使用 if-elif-else 语句进行条件分支。

 1def switch_example(value):
 2    if value == 1:
 3        return "Value is one"
 4    elif value == 2:
 5        return "Value is two"
 6    elif value == 3:
 7        return "Value is three"
 8    else:
 9        return "Unknown value"
10
11print(switch_example(1))  # Output: Value is one
12print(switch_example(4))  # Output: Unknown value

方法 2:使用字典

通过将函数或值映射到字典,可以创建一个类似于 switch 语句的结构。当您想对特定值执行不同操作时,这非常方便。

 1def case_one():
 2    return "Value is one"
 3
 4def case_two():
 5    return "Value is two"
 6
 7def case_default():
 8    return "Unknown value"
 9
10def switch_example(value):
11    switch_dict = {
12        1: case_one,
13        2: case_two
14    }
15
16    # Use get() method to retrieve the corresponding function from the dictionary
17    # If the value is not found in the dictionary, use case_default as a fallback
18    return switch_dict.get(value, case_default)()
19
20print(switch_example(1))  # Output: Value is one
21print(switch_example(3))  # Output: Unknown value

方法 3:match 语句(Python 3.10 及更高版本)

match 语句是在 Python 3.10 中引入的。这是一种模式匹配语法,提供了类似于 switch 语句的功能。

 1def switch_example(value):
 2    match value:
 3        case 1:
 4            return "Value is one"
 5        case 2:
 6            return "Value is two"
 7        case 3:
 8            return "Value is three"
 9        case _:
10            return "Unknown value"
11
12print(switch_example(1))  # Output: Value is one
13print(switch_example(4))  # Output: Unknown value

总结

  • if-elif-else 语句:简单且适用于多种情况。
  • 字典:使用函数或值的映射来实现高效的分支。
  • match 语句:在 Python 3.10 及更高版本中允许更直观的分支。最接近 switch 语句。

Python 中的 For 循环

Python 的 for 语句用于遍历可迭代对象的每一个元素,如列表、字符串或字典。for 语句的基本语法如下:。

1# Loop through each item in the iterable
2for variable in iterable:
3    # Execute this block of code for each item in the iterable
4    code_to_execute

以下是一些具体的示例:。

列表示例

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

此代码对列表 fruits 中的每个元素调用 print 函数,输出每个水果的名称。

range() 示例

range() 函数生成指定范围内的整数,非常适合进行数字迭代。

1for i in range(5):
2    print(i)

range(5) 生成从 0 到 4 的整数。在这种情况下,将依次输出 0, 1, 2, 3, 4

字典示例

对于字典,默认会迭代键,但您也可以检索键值对。

1person = {"name": "Alice", "age": 25}
2for key in person:
3    print(key, person[key])

或者,使用 items() 方法同时获取键和值。

1person = {"name": "Alice", "age": 25}
2for key, value in person.items():
3    print(key, value)

嵌套的 for 循环

也可以嵌套 for 循环来执行复杂的迭代过程。

1matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2for row in matrix:
3    for num in row:
4        print(num)

此代码迭代列表 matrix 的每一行,并依次输出每行中的数字。

使用 continue 跳过一轮迭代,使用 break 终止循环

for 循环中使用 continue 会跳过当前的迭代并进入下一次迭代。此外,使用 break 将完全终止循环。

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

在此示例中,当 i 等于 5 时循环会跳过,而在 i 等于 8 时循环会终止。因此,输出将是 0, 1, 2, 3, 4, 6, 7

Python 的 for 循环非常灵活,可以用于多种场景。根据你想执行的迭代处理类型,它可以与列表、字典、字符串和 range() 一起使用。

Python 中的 while 循环

在 Python 中,while 循环是一种控制结构,只要条件为 True,它就会重复执行代码块中的代码。while 循环的基本语法如下:。

1while condition:
2    # This block of code will be executed repeatedly as long as the condition is true
3    statement1
4    statement2
5    ...

示例:

在以下示例中,使用 while 循环输出从 1 到 5 的数字。

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

此代码的工作方式如下。

  • i 为 1 开始,在 i 小于等于 5 时打印 i,每次将 i 增加 1。

注意:

在使用 while 语句时,需要注意以下几点:。

  1. 注意死循环

    • 如果 while 循环中的条件始终为 True,则会导致死循环。必须执行适当的操作来更改条件;否则程序将不会停止。
  2. 使用 breakcontinue

    • break 用于提前退出循环。
    • continue 跳过当前循环,直接开始下一次循环。要小心,因为不正确的循环条件可能会导致死循环。

break 的示例:

1i = 1
2while i <= 5:
3    if i == 3:
4        break  # Exit the loop when i becomes 3
5    print(i)
6    i += 1
  • 在这种情况下,输出 12 之后,当 i 变为 3 时,循环结束。

continue 的示例:

1i = 0
2while i < 5:
3    i += 1
4    if i == 3:
5        # Skip the print statement and move to the next loop iteration when i is 3
6        continue
7    print(i)
  • 在这种情况下,只有在 3 时跳过输出,结果为 1, 2, 4, 5
  • 在循环开始时增加 i 的值,即使执行了 continue,计数器也会前进,从而避免死循环。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video