理解顺序流程并引入条件逻辑
在这一步中,我们将探索编程中顺序流程(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)。