实现 if 语句
在这一步中,你将学习如何在 Python 中使用 if 语句来控制程序的流程。if 语句允许你仅在某个条件为真时执行一段代码。
if 语句的基本语法如下:
if condition:
## Code to execute if the condition is true
condition 是一个布尔表达式,其求值结果为 True 或 False。如果条件为 True,则执行缩进块内的代码;如果条件为 False,则跳过该块内的代码。
让我们创建一个简单的示例来演示 if 语句的工作原理。你将修改上一步创建的 conditions.py 脚本。
- 在 VS Code 中打开
conditions.py 文件。
- 修改代码以包含以下内容:
x = 5
y = 10
if x < y:
print("x is less than y")
这段代码检查 x 是否小于 y。如果是,则打印消息 "x is less than y"。
保存更改并再次运行脚本:
python ~/project/conditions.py
你应该会看到以下输出:
x is less than y
这个输出表明 if 语句内的代码被执行了,因为条件 x < y 为真。
你还可以在 if 语句中添加 else 子句。else 子句允许你在条件为假时执行不同的代码块。
if-else 语句的语法如下:
if condition:
## Code to execute if the condition is true
else:
## Code to execute if the condition is false
让我们修改 conditions.py 脚本以包含 else 子句。
- 在 VS Code 中打开
conditions.py 文件。
- 修改代码以包含以下内容:
x = 15
y = 10
if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")
这段代码检查 x 是否小于 y。如果是,则打印消息 "x is less than y";否则,打印消息 "x is greater than or equal to y"。
保存更改并再次运行脚本:
python ~/project/conditions.py
你应该会看到以下输出:
x is greater than or equal to y
这个输出表明 else 子句内的代码被执行了,因为条件 x < y 为假。
最后,你可以在 if 语句中添加 elif(else if)子句。elif 子句允许你依次检查多个条件。
if-elif-else 语句的语法如下:
if condition1:
## Code to execute if condition1 is true
elif condition2:
## Code to execute if condition1 is false and condition2 is true
else:
## Code to execute if both condition1 and condition2 are false
让我们修改 conditions.py 脚本以包含 elif 子句。
- 在 VS Code 中打开
conditions.py 文件。
- 修改代码以包含以下内容:
x = 10
y = 10
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
这段代码检查 x 是否小于 y。如果是,则打印消息 "x is less than y";如果 x 大于 y,则打印消息 "x is greater than y";否则,打印消息 "x is equal to y"。
保存更改并再次运行脚本:
python ~/project/conditions.py
你应该会看到以下输出:
x is equal to y
这个输出表明 else 子句内的代码被执行了,因为条件 x < y 和 x > y 都为假。
if 语句对于创建能够做出决策并对不同情况做出响应的程序至关重要。在下一步中,你将学习如何使用 and 和 or 运算符在 if 语句中组合多个条件。