Python 中的条件语句

PythonBeginner
立即练习

介绍

在这个 Lab 中,你将学习如何使用条件语句来控制 Python 程序的流程。我们将从理解顺序程序执行(sequential program execution)的概念开始,然后介绍条件逻辑(conditional logic),它使程序能够做出决策。

你将使用 ifif-else 语句来实现单分支和双分支逻辑,并使用 if-elif-else 来探索多分支逻辑。这个 Lab 还将涵盖嵌套的 if 语句、pass 语句,并介绍 Python 3.10 及更高版本中可用的 match-case 语句。到这个 Lab 结束时,你将能够编写 Python 代码,根据特定条件执行不同的指令块。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 100%。获得了学习者 100% 的好评率。

理解顺序流程并引入条件逻辑

在这一步中,我们将探索编程中顺序流程(sequential flow)的概念,并介绍条件逻辑(conditional logic),它允许程序做出决策。

顺序流程是最基本的程序执行类型。指令按顺序执行,从上到下。

Lab 环境已经在 ~/project 目录下为你创建了一个名为 sequential.py 的文件。请在左侧面板的 WebIDE 文件浏览器中找到此文件并打开它。

将以下代码添加到 sequential.py 中:

print("First instruction")
print("Second instruction")
print("Third instruction")

保存文件。要运行脚本,请打开 WebIDE 中的集成终端(integrated terminal),并执行以下命令:

python ~/project/sequential.py

你将看到输出按照 print 语句在脚本中出现的顺序精确打印出来:

First instruction
Second instruction
Third instruction

这演示了顺序流程。然而,程序通常需要根据某些条件表现出不同的行为。这就是条件逻辑发挥作用的地方。Python 中最基本的条件语句是 if 语句,它仅在指定的条件为真(true)时才执行一个代码块。

if 语句的基本语法如下:

if condition:
    ## 如果条件为真时执行的代码
    ## 此代码块必须缩进

现在,用以下代码替换 sequential.py 的内容,以包含一个 if 语句:

x = 10

print("Before the if statement")

if x > 5:
    print("x is greater than 5")

print("After the if statement")

保存文件并再次运行它:

python ~/project/sequential.py

输出将是:

Before the if statement
x is greater than 5
After the if statement

条件 x > 5 为真,因此执行 if 语句内部缩进的代码块。

现在,让我们看看当条件为假(false)时会发生什么。通过将 x 的值更改为 3 来修改 sequential.py

x = 3

print("Before the if statement")

if x > 5:
    print("x is greater than 5")

print("After the if statement")

保存文件并运行它:

python ~/project/sequential.py

输出将是:

Before the if statement
After the if statement

这次,条件 x > 5 为假,因此 if 语句内部的代码块被跳过。这个简单的例子说明了 if 语句如何为我们的程序引入决策制定(decision-making)。

使用 if 和 if-else 实现单分支和双分支逻辑

在这一步中,我们将重点关注使用 ifif-else 语句来实现单分支(single-branch)和双分支(dual-branch)逻辑。

if 语句允许单分支执行。让我们使用已经为你准备好的 branching.py 文件。从文件浏览器中打开 branching.py

将以下代码添加到 branching.py 中,以演示单分支 if 语句:

score = 85

if score >= 70:
    print("Congratulations! You passed.")

print("End of program.")

保存文件,并从终端运行它:

python ~/project/branching.py

输出将是:

Congratulations! You passed.
End of program.

由于 score 是 85,条件为真,祝贺信息被打印出来。

虽然 if 很有用,但我们通常需要在条件为假时执行另一个代码块。这时 if-else 语句就派上用场了,它提供了双分支逻辑。

if-else 语句的语法如下:

if condition:
    ## 如果条件为真时执行的代码
else:
    ## 如果条件为假时执行的代码

让我们修改 branching.py 以使用 if-else 语句。将当前内容替换为以下内容:

score = 85

if score >= 70:
    print("Congratulations! You passed.")
else:
    print("Keep trying. You can do better.")

print("End of program.")

保存并运行脚本。当 score 为 85 时,if 块运行:

Congratulations! You passed.
End of program.

现在,为了测试 else 块,请在 branching.py 中将 score 修改为 65

score = 65

if score >= 70:
    print("Congratulations! You passed.")
else:
    print("Keep trying. You can do better.")

print("End of program.")

保存文件并再次运行它:

python ~/project/branching.py

输出现在将是:

Keep trying. You can do better.
End of program.

由于 score 是 65,if 条件为假,else 块中的代码被执行。if-else 语句对于处理两种可能的结果至关重要。

使用 if-elif-else 实现多分支逻辑

在这一步中,我们将学习如何使用 if-elif-else 语句来处理多于两种可能结果的情况,它提供了多分支逻辑(multi-branch logic)。

if-elif-else 结构会顺序检查条件。如果 if 条件为假(false),它会检查第一个 elif("else if" 的缩写)条件,依此类推。如果所有条件都不为真,则执行 else 代码块。

基本语法如下:

if condition1:
    ## 如果 condition1 为真时执行
elif condition2:
    ## 如果 condition1 为假且 condition2 为真时执行
else:
    ## 如果所有先前条件都为假时执行

在 WebIDE 中打开 multibranch.py 文件。我们将编写一个脚本,根据一个数值分数来确定一个字母等级。添加以下代码:

score = 88

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

保存文件,并从终端运行它:

python ~/project/multibranch.py

输出将是:

Grade: B
Grading complete.

程序检查 score >= 90(假),然后检查 score >= 80(真),打印 "Grade: B",并跳过该条件链的其余部分。

现在,让我们测试 else 块。修改 multibranch.py 将分数设置为 55

score = 55

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

保存并运行脚本:

python ~/project/multibranch.py

输出将是:

Grade: F
Grading complete.

最后,为了准备验证,在 multibranch.py 中将分数更改为 75

score = 75

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

print("Grading complete.")

保存并最后一次运行脚本:

python ~/project/multibranch.py

输出将是:

Grade: C
Grading complete.

if-elif-else 结构对于处理多个不同的情况非常强大。请记住,只有第一个为真的条件的对应代码块才会被执行。

探索嵌套 if 语句和 pass 语句

在这一步中,我们将探索嵌套 if 语句(即一个 if 语句放置在另一个内部)以及学习 pass 语句。

当你需要检查一个条件,并且如果该条件为真时需要检查另一个子条件时,嵌套 if 语句非常有用。

在 WebIDE 中打开 nested_if.py 文件。添加以下代码,该代码根据年龄和公民身份检查投票资格。

age = 20
is_citizen = True

if age >= 18:
    print("You are old enough to vote.")
    if is_citizen:
        print("You are also a citizen.")
        print("You are eligible to vote.")
    else:
        print("You are not a citizen.")
        print("You are not eligible to vote.")
else:
    print("You are not old enough to vote.")
    print("You are not eligible to vote.")

print("Voting eligibility check complete.")

保存文件并运行它:

python ~/project/nested_if.py

输出将是:

You are old enough to vote.
You are also a citizen.
You are eligible to vote.
Voting eligibility check complete.

外部条件(age >= 18)和内部条件(is_citizen)都为真。

现在,我们来看一下 pass 语句。pass 语句是一个空操作;执行它时什么也不会发生。当语法要求存在一个语句,但你尚未为其编写代码时,它是一个有用的占位符。

用使用 pass 的这个示例替换 nested_if.py 的内容:

age = 18

if age >= 18:
    pass ## Placeholder for future code
else:
    print("You are not old enough to vote.")

print("Check complete.")

保存并运行脚本:

python ~/project/nested_if.py

输出将是:

Check complete.

if 条件为真,因此执行 pass 语句(什么也不做),else 代码块被跳过。

最后,为了准备验证,修改 nested_if.py,使用原始逻辑,但设置一个不满足第一个检查的年龄。

age = 16
is_citizen = True

if age >= 18:
    print("You are old enough to vote.")
    if is_citizen:
        print("You are eligible to vote.")
    else:
        print("You are not eligible to vote.")
else:
    print("You are not old enough to vote.")
    print("You are not eligible to vote.")

print("Voting eligibility check complete.")

保存并运行脚本:

python ~/project/nested_if.py

输出将是:

You are not old enough to vote.
You are not eligible to vote.
Voting eligibility check complete.

在这里,外部 if 条件(age >= 18)为假,因此执行外部 else 代码块,内部的 if-else 结构被完全跳过。

介绍 match-case 语句 (Python 3.10+)

在这一步中,我们将探索 match-case 语句,这是 Python 3.10 中引入的用于结构化模式匹配(structural pattern matching)的特性。对于某些场景,它为冗长的 if-elif-else 链提供了一个更具可读性的替代方案。

match-case 语句将一个值与一系列模式进行比较,并执行第一个匹配模式的代码块。

基本语法如下:

match value:
    case pattern1:
        ## pattern1 的代码
    case pattern2:
        ## pattern2 的代码
    case _:
        ## 没有匹配时的代码(通配符)

在 WebIDE 中打开 match_case.py 文件。添加以下代码,根据数字打印星期几。

day_number = 3

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

保存文件并运行它。此环境中的 python 命令默认使用兼容的版本。

python ~/project/match_case.py

输出将是:

Wednesday
Day check complete.

3 匹配 case 3:,因此打印 "Wednesday"。

现在,我们来测试通配符情况。修改 match_case.py 使用一个无效的数字:

day_number = 10

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

保存并运行脚本:

python ~/project/match_case.py

输出将是:

Invalid day number
Day check complete.

由于 10 不匹配任何特定的 case,因此匹配到通配符 case _:

最后,为了准备验证,在 match_case.py 中将 day_number 更改为 6

day_number = 6

match day_number:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case 3:
        print("Wednesday")
    case 4:
        print("Thursday")
    case 5:
        print("Friday")
    case 6:
        print("Saturday")
    case 7:
        print("Sunday")
    case _:
        print("Invalid day number")

print("Day check complete.")

保存并最后一次运行脚本:

python ~/project/match_case.py

输出将是:

Saturday
Day check complete.

与冗长的 if-elif-else 链相比,match-case 语句可以成为处理多个特定值的更清晰的方法。

总结

在这个实验中,你学习了如何控制 Python 程序的流程。你从顺序程序流开始,然后转向条件逻辑。你使用 if 实现了单分支逻辑,使用 if-else 实现了双分支逻辑,使用 if-elif-else 实现了多分支逻辑。你还探索了如何使用嵌套 if 语句创建更复杂的决策结构,以及如何使用 pass 语句作为代码占位符。最后,你了解了 match-case 语句作为一种用于基于模式的分支的现代替代方案。你现在已经具备了编写能够根据特定条件做出决策并执行不同代码路径的 Python 程序的能力。