Python while 循环
- Python while 循环用于重复执行一段代码,直到指定的条件为假为止。
- 当我们不知道代码块需要执行多少次时,可以使用 while 循环。
- 编写 while 循环条件时应该格外小心,如果条件永远不会返回 False,while 循环就会进入无限循环。
- Python 中的每个对象都有一个布尔值。如果该值为 0 或 None,则布尔值为 False;否则,布尔值为 True。
- 我们可以通过实现函数来定义对象的布尔值__bool__()。
- 我们使用保留关键字while来实现 Python 中的 while 循环。
- 我们可以使用break 语句终止 while 循环。
- 我们可以在 while 循环中使用 continue 语句来跳过代码块的执行。
- Python支持嵌套while循环。
Python while 循环语法
python
while condition:
# while block codewhile循环流程图

Python while 循环示例
假设我们需要打印一条消息指定的次数。我们可以使用 while 循环来编写这个实用函数。
python
def print_msg(count, msg):
while count > 0:
print(msg)
count -= 1
print_msg(3, "Hello World")输出:

while 循环并带有 break 语句
有时我们希望某个代码块无限期地执行下去,直到收到退出信号。我们可以使用“while True”代码块和break语句来实现这个功能。
这是一个实用脚本示例,它接收用户输入(整数)并打印其平方值。当用户输入 0 时,程序终止。
python
while True:
i = input('Please enter an integer (0 to exit):\n')
i = int(i)
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')以下是该程序一次示例运行的输出结果。

Python while 循环和 continue 语句
假设我们希望上述脚本仅处理正数。在这种情况下,我们可以使用 continue 语句来跳过用户输入负数时的执行。
python
while True:
i = input('Please enter an integer (0 to exit):\n')
i = int(i)
if i < 0:
print("The program works with Positive Integers only.")
continue
if i == 0:
print("Exiting the Program")
break
print(f'{i} square is {i ** 2}')输出:
shell
Please enter an integer (0 to exit):
5
5 square is 25
Please enter an integer (0 to exit):
-10
The program works with Positive Integers only.
Please enter an integer (0 to exit):
0
Exiting the ProgramPython while 循环和 else 语句
我们可以在 while 循环中使用 else 代码块。当 while 循环正常终止时(即条件为假时),else 代码块中的代码会被执行。
如果由于错误或 break 语句而终止 while 循环,则 else 代码块不会执行。
python
count = 5
while count > 0:
print("Welcome")
count -= 1
else:
print("Exiting the while Loop")输出:

让我们看看当 while 循环因错误而终止时会发生什么。
python
count = 5
while count > 0:
print("Welcome")
count -= 1
if count == 2:
raise ValueError
else:
print("Exiting the while Loop")输出:
shell
Welcome
Welcome
Welcome
Traceback (most recent call last):
File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/while-loop.py", line 7, in <module>
raise ValueError
ValueError
让我们修改程序,使其跳出 while 循环。
python
count = 5
while count > 0:
print("Welcome")
count -= 1
if count == 2:
break
else:
print("Exiting the while Loop")输出:
shell
Welcome
Welcome
Welcome嵌套 while 循环示例
我们还可以使用嵌套的while循环。下面是一个使用嵌套while循环生成元组列表的示例。
python
i = 3
j = 3
list_tuples = []
while i > 0:
while j > 0:
t = (i, j)
list_tuples.append(t)
j -= 1
j = 3
i -= 1
print(list_tuples)输出:
shell
[(3, 3), (3, 2), (3, 1), (2, 3), (2, 2), (2, 1), (1, 3), (1, 2), (1, 1)]结论
Python 的 while 循环用于执行一段代码块指定的次数。我们可以将 break 和 continue 语句与 while 循环结合使用。当 while 循环正常终止时,else 代码块会被执行。while 循环还可以用于无限循环地运行脚本。