介绍
在这个实验中,你将获得对 Python 中循环(loops)的基本理解,循环是自动化重复任务的关键工具。我们将从探索 for 循环和迭代(iteration)的概念开始,学习如何处理列表(lists)和字符串(strings)等序列。
接下来,你将了解如何将 range() 函数与 for 循环结合使用,以生成数字序列。然后,我们将介绍用于基于条件的重复的 while 循环。最后,你将学习如何使用 break 和 continue 语句来控制 for 循环和 while 循环的流程。
介绍 For 循环和迭代
在这一步中,你将学习 Python 中的 for 循环。for 循环用于遍历一个序列(sequence),例如列表(list)、元组(tuple)或字符串(string)。遍历意味着对序列中的每个元素逐一执行一个操作。
首先,让我们使用 for 循环来打印列表中每个元素。
在左侧的 WebIDE 文件浏览器中,你会看到一个文件列表。找到并打开名为 for_loop_example.py 的文件。向其中添加以下 Python 代码:
## Define a list of numbers
numbers = [1, 2, 3, 4, 5]
## The for loop iterates over each item in the 'numbers' list.
## In each iteration, the current item is assigned to the 'number' variable.
for number in numbers:
## This code block is executed for each item.
print(number)
按 Ctrl + S 保存文件。
要运行脚本,请点击 WebIDE 顶部的 Terminal -> New Terminal 打开集成终端(integrated terminal)。然后,执行以下命令:
python for_loop_example.py
你应该会看到以下输出,每个数字都打印在新的一行上:
1
2
3
4
5
for 循环也可以遍历字符串。让我们在一个新文件中尝试一下。从文件浏览器中打开 string_loop.py 文件,并添加以下代码:
## Define a string
message = "Hello"
## Iterate over each character in the 'message' string
for char in message:
## Print each character
print(char)
保存文件,然后从终端运行它:
python string_loop.py
输出将是:
H
e
l
l
o
这表明 for 循环可以处理任何序列,将字符串视为字符序列。
在 For 循环中使用 range() 函数
range() 函数是一个强大的工具,常与 for 循环一起使用以生成数字序列。当你需要重复执行某个操作特定的次数时,这非常有用。
range() 函数有三种使用方式:
range(stop): 生成从 0 开始到stop之前(不包括stop)的数字。range(start, stop): 生成从start开始到stop之前(不包括stop)的数字。range(start, stop, step): 生成从start开始到stop之前(不包括stop)的数字,步长(increment)为step。
让我们看看这是如何工作的。从文件浏览器中打开 range_example.py 文件,并添加以下代码:
## Use range(stop) to print numbers from 0 to 4
print("Numbers from 0 to 4:")
for i in range(5):
print(i)
print("\n" + "="*20 + "\n") ## A separator for clarity
## Use range(start, stop) to print numbers from 2 to 5
print("Numbers from 2 to 5:")
for i in range(2, 6):
print(i)
print("\n" + "="*20 + "\n") ## A separator for clarity
## Use range(start, stop, step) to print odd numbers from 1 to 9
print("Odd numbers from 1 to 9:")
for i in range(1, 10, 2):
print(i)
保存文件,然后从终端运行它:
python range_example.py
你应该会看到以下输出:
Numbers from 0 to 4:
0
1
2
3
4
====================
Numbers from 2 to 5:
2
3
4
5
====================
Odd numbers from 1 to 9:
1
3
5
7
9
请注意,stop 值永远不会包含在序列中。如果你需要固定次数地执行某个操作,但不需要计数器的值,你可以使用下划线 _ 作为变量名。这是 Python 中的一个常见约定。
## This loop will execute 5 times
for _ in range(5):
print("Hello")
介绍 While 循环
在这一步中,你将学习 while 循环。与预定迭代次数的 for 循环不同,while 循环会持续执行,直到指定的条件保持为 True。
while 循环的基本语法如下:
while condition:
## 要执行的代码
## 重要提示:更新一个变量,使其最终使条件变为 False
确保条件最终会变为 False 至关重要。否则,你将创建一个无限循环(infinite loop),这将导致你的程序永远运行下去。
让我们创建一个使用 while 循环从 1 打印到 5 的脚本。打开 while_loop_example.py 文件,并添加以下代码:
## Initialize a counter variable
count = 1
## The loop continues as long as 'count' is less than or equal to 5
while count <= 5:
## Print the current value of count
print(count)
## Increment count by 1. This is essential to prevent an infinite loop.
count = count + 1 ## This can also be written as count += 1
保存文件,然后从终端运行它:
python while_loop_example.py
你应该会看到以下输出:
1
2
3
4
5
循环的工作原理如下:
count初始化为1。- 检查条件
count <= 5。1 <= 5为True,因此执行循环体。 - 打印
1,并将count增量更新为2。 - 再次检查条件。
2 <= 5为True,因此循环继续。 - 此过程重复,直到
count变为6。 - 当
count为6时,条件6 <= 5为False,循环终止。
当你预先知道迭代次数时,使用 for 循环。当重复执行依赖于在执行期间可能发生变化的条件时,使用 while 循环。
使用 break 和 continue 控制循环流程
Python 提供了 break 和 continue 两个语句来改变循环的正常流程。
break 语句会立即终止其所在的循环。程序执行会跳转到循环之后的第一个语句。
我们来看一个例子。打开 break_example.py 文件并添加这段代码,它会在满足特定条件时停止循环:
## Iterate through numbers from 0 to 9
for i in range(10):
## If i is 5, the 'if' condition becomes True
if i == 5:
print(f"Breaking loop at i = {i}")
## The break statement exits the loop immediately
break
print(i)
print("Loop finished.")
保存文件并运行它:
python break_example.py
输出将是:
0
1
2
3
4
Breaking loop at i = 5
Loop finished.
当 i 变为 5 时,循环停止了,数字 5 到 9 从未被打印出来。
continue 语句会跳过当前迭代的剩余部分,直接进入下一次迭代。
让我们看看如何使用 continue 来跳过打印特定数字。打开 continue_example.py 文件并添加以下代码:
## Initialize a counter
count = 0
## Loop while count is less than 10
while count < 10:
count += 1
## If count is 5, the 'if' condition becomes True
if count == 5:
print(f"Skipping iteration at count = {count}")
## The continue statement skips the rest of this iteration
continue
## This line is skipped when count is 5
print(count)
print("Loop finished.")
保存文件并运行它:
python continue_example.py
输出将是:
1
2
3
4
Skipping iteration at count = 5
6
7
8
9
10
Loop finished.
在这种情况下,当 count 为 5 时,执行了 continue 语句。这导致该次迭代中的 print(count) 语句被跳过,循环进入下一次迭代,此时 count 变为 6。
总结
在这个实验(Lab)中,你学习了 Python 中循环的基础知识。你从 for 循环开始,使用它来迭代列表和字符串等序列。然后,你探索了 range() 函数,用于为 for 循环创建数字序列。
接下来,你学习了 while 循环,用于创建只要条件为真就一直运行的循环。最后,你学会了如何使用 break 语句提前退出循环,以及使用 continue 语句跳过某次迭代来控制循环的执行。这些概念是编写高效且强大的 Python 程序的基础。



