Python 控制流

Python 控制流

控制流是单个语句、指令或函数调用被执行或求值的顺序。Python 程序的控制流由条件语句、循环和函数调用来调节。

比较运算符

运算符含义
==等于
!=不等于
<小于
>大于
<=小于或等于
>=大于或等于

这些运算符根据你给它们的值评估为 True 或 False。

示例:

42 == 42
True
40 == 42
False
'hello' == 'hello'
True
'hello' == 'Hello'
False
'dog' != 'cat'
True
42 == 42.0
True
42 == '42'
False
测验

登录后即可答题并追踪学习进度

'hello' == 'Hello' 的评估结果是什么?
A. True
B. False
C. None
D. 抛出错误

布尔运算符

有三个布尔运算符:andornot。 按优先级从高到低依次是 notandor

and 运算符的真值表

表达式评估结果
True and TrueTrue
True and FalseFalse
False and TrueFalse
False and FalseFalse

or 运算符的真值表

表达式评估结果
True or TrueTrue
True or FalseTrue
False or TrueTrue
False or FalseFalse

not 运算符的真值表

表达式评估结果
not TrueFalse
not FalseTrue

混合运算符

你可以混合使用布尔运算符和比较运算符:

(4 < 5) and (5 < 6)
True
(4 < 5) and (9 < 6)
False
(1 == 2) or (2 == 2)
True

此外,你可以在一个表达式中混合使用多个布尔运算符以及比较运算符:

2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
# 在下面的语句中,3 < 4 and 5 > 5 首先被执行,评估为 False
# 然后 5 > 4 返回 True,所以 True or False 的结果是 True
5 > 4 or 3 < 4 and 5 > 5
True
# 现在括号内的语句首先被执行,所以 True and False 返回 False。
(5 > 4 or 3 < 4) and 5 > 5
False

if 语句

if 语句评估一个表达式,如果该表达式为 True,则执行接下来的缩进代码:

# if 语句:当条件为 True 时执行代码块
name = 'Debora'

if name == 'Debora':  # 检查 name 是否等于 'Debora'
   print('Hi, Debora')  # 如果条件为 True,则执行此行
Hi, Debora
if name != 'George':
   print('You are not George')
You are not George

只有当 if 和所有 elif 表达式的评估结果都为 False 时,else 语句才会执行:

# if-else:根据条件执行不同的代码
name = 'Debora'

if name == 'George':
   print('Hi, George.')
else:  # 如果 if 条件为 False,则执行
   print('You are not George')
You are not George
测验

登录后即可答题并追踪学习进度

在 if-else 语句中,else 块何时执行?
A. 总是
B. 仅当 if 条件(以及所有 elif 条件(如果存在))为 False
C. 仅当 if 条件为 True
D. 从不

只有在 if 语句的表达式为 False 之后,才会评估并执行 elif 语句:

# if-elif:按顺序检查多个条件
name = 'George'

if name == 'Debora':
   print('Hi Debora!')
elif name == 'George':  # 仅在前一个条件为 False 时检查
   print('Hi George!')
Hi George!

elifelse 部分是可选的。

name = 'Antony'

if name == 'Debora':
   print('Hi Debora!')
elif name == 'George':
   print('Hi George!')
else:
   print('Who are you?')
Who are you?

三元条件运算符

许多编程语言都有一个三元运算符,用于定义条件表达式。最常见的用法是创建一个简洁的简单条件赋值语句。换句话说,如果条件为真,它提供单行代码来评估第一个表达式,否则评估第二个表达式。

<expression1> if <condition> else <expression2>

示例:

age = 15

# 这个 if 语句:
if age < 18:
   print('kid')
else:
   print('adult')
kid
# 三元运算符:单行条件表达式
# 语法:value_if_true if condition else value_if_false
print('kid' if age < 18 else 'adult')
kid

三元运算符可以链式使用:

age = 15

# 这个三元运算符:
print('kid' if age < 13 else 'teen' if age < 18 else 'adult')
teen
# 等同于这个 if 语句:
if age < 13:
    print('kid')
else:
    if age < 18:
        print('teen')
    else:
        print('adult')
teen

Switch-Case 语句

Switch-Case 语句

在计算机编程语言中,switch 语句是一种选择控制机制,用于通过搜索和映射来允许变量或表达式的值改变程序的控制流执行。

Switch-Case 语句,或结构化模式匹配,首次通过 PEP 622 引入于 2020 年,并于 2022 年 9 月随 Python 3.10 正式发布。

官方教程

PEP 636 为 Python 模式匹配或 Switch-Case 语句提供了官方教程。

匹配单个值

response_code = 201
match response_code:
    case 200:
        print("OK")
    case 201:
        print("Created")
    case 300:
        print("Multiple Choices")
    case 307:
        print("Temporary Redirect")
    case 404:
        print("404 Not Found")
    case 500:
        print("Internal Server Error")
    case 502:
        print("502 Bad Gateway")
Created

使用 or 模式匹配

在此示例中,管道字符 (|or) 允许 Python 为两个或多个情况返回相同的响应。

response_code = 502
match response_code:
    case 200 | 201:
        print("OK")
    case 300 | 307:
        print("Redirect")
    case 400 | 401:
        print("Bad Request")
    case 500 | 502:
        print("Internal Server Error")
Internal Server Error

按可迭代对象的长度匹配

today_responses = [200, 300, 404, 500]
match today_responses:
    case [a]:
            print(f"One response today: {a}")
    case [a, b]:
            print(f"Two responses today: {a} and {b}")
    case [a, b, *rest]:
            print(f"All responses: {a}, {b}, {rest}")
All responses: 200, 300, [404, 500]

默认值

下划线符号 (_) 用于定义默认情况:

response_code = 800
match response_code:
    case 200 | 201:
        print("OK")
    case 300 | 307:
        print("Redirect")
    case 400 | 401:
        print("Bad Request")
    case 500 | 502:
        print("Internal Server Error")
    case _:
        print("Invalid Code")
Invalid Code

匹配内置类

response_code = "300"
match response_code:
    case int():
            print('Code is a number')
    case str():
            print('Code is a string')
    case _:
            print('Code is neither a string nor a number')
Code is a string

保护 Match-Case 语句

response_code = 300
match response_code:
    case int() if response_code > 99 and response_code < 500:
            print('Code is a valid number')
    case _:
            print('Code is an invalid number')
Code is a valid number

while 循环语句

while 语句用于重复执行,只要一个表达式为 True

# while 循环:只要条件为 True,就重复执行代码
spam = 0
while spam < 5:  # 只要 spam 小于 5 就继续
    print('Hello, world.')
    spam = spam + 1  # 增加计数器以避免无限循环
Hello, world.
Hello, world.
Hello, world.
Hello, world.
Hello, world.
测验

登录后即可答题并追踪学习进度

while 循环做什么?
A. 只要条件为 True 就重复执行代码
B. 只执行代码一次
C. 执行固定次数的代码
D. 跳过代码执行

break 语句

如果执行到达 break 语句,它会立即退出 while 循环的子句:

# break 语句:遇到时立即退出循环
while True:  # 无限循环
    name = input('Please type your name: ')
    if name == 'your name':
        break  # 立即退出循环

print('Thank you!')
Please type your name: your name
Thank you!

continue 语句

当程序执行到达 continue 语句时,程序执行立即跳回到循环的开头。

# continue 语句:跳过循环迭代的其余部分并开始下一次迭代
while True:
    name = input('Who are you? ')
    if name != 'Joe':
        continue  # 跳到下一次迭代,不询问密码
    password = input('Password? (It is a fish.): ')
    if password == 'swordfish':
        break  # 密码正确时退出循环

print('Access granted.')
Who are you? Charles
Who are you? Debora
Who are you? Joe
Password? (It is a fish.): swordfish
Access granted.

For 循环

for 循环迭代 listtupledictionarysetstring

# for 循环:迭代序列中的每个项目
pets = ['Bella', 'Milo', 'Loki']
for pet in pets:  # 循环遍历列表中的每只宠物
    print(pet)  # 打印每只宠物的名字
Bella
Milo
Loki
测验

登录后即可答题并追踪学习进度

for 循环迭代什么?
A. 仅数字
B. 仅字符串
C. 任何可迭代序列(列表、元组、字典、集合、字符串等)
D. 仅列表

range() 函数

range() 函数返回一个数字序列。它从 0 开始,以 1 递增,并在指定的数字之前停止:

for i in range(5):
    print(f'Will stop at 5! or 4? ({i})')
Will stop at 5! or 4? (0)
Will stop at 5! or 4? (1)
Will stop at 5! or 4? (2)
Will stop at 5! or 4? (3)
Will stop at 5! or 4? (4)
测验

登录后即可答题并追踪学习进度

range(5) 生成什么?
A. 从 1 到 5 的数字
B. 从 0 到 4 的数字
C. 从 0 到 5 的数字
D. 五个随机数

range() 函数也可以修改其 3 个默认参数。前两个是 startstop 值,第三个是 step 参数。step 是每次迭代后变量增加的量。

# range(start, stop, step)
for i in range(0, 10, 2):
   print(i)
0
2
4
6
8

你甚至可以使用负数作为 step 参数,使 for 循环倒数而不是递增。

for i in range(5, -1, -1):
    print(i)
5
4
3
2
1
0

For else 语句

这允许指定一个语句,在循环完全执行时执行。仅在循环中可能发生 break 条件时才有用:

for i in [1, 2, 3, 4, 5]:
   if i == 3:
       break
else:
   print("only executed when no item is equal to 3")

使用 sys.exit() 结束程序

exit() 函数允许退出 Python。

import sys

while True:
    feedback = input('Type exit to exit: ')
    if feedback == 'exit':
        print(f'You typed {feedback}.')
        sys.exit()
Type exit to exit: open
Type exit to exit: close
Type exit to exit: exit
You typed exit.

相关链接