Python带有else子句的循环语句
for…else
摘要:在本教程中,你将学习 Python 的 for...else 语句以及如何有效地使用它。
Python for…else 语句介绍
在 Python 中,for 语句可以有一个可选的 else 子句,如果你来自其他语言(如 Java 或 C#),可能对此不太熟悉。
以下是带有 else 子句的 for 语句的语法:
for item in iterables:# Process itemif condition:break # Terminate the loop prematurely
else:# Executed if the loop completes without a break
在此语法中:
- Python 仅在
for循环遍历完可迭代对象中的所有项且未遇到break语句时,才会执行else块。 - 如果 Python 遇到
break语句,它将完全跳过else块。 - 如果可迭代对象没有任何项,Python 会立即执行
else块。
与 break 语句不同,continue 语句不会提前结束循环。因此,如果循环正常完成,else 块将会执行。
以下流程图说明了 for...else 语句的逻辑:

如果你知道如何有效地运用 else 子句,那么它在某些情况下会非常有用。
Python for…else 示例
假设你有一个人员列表,其中每个人都是一个包含姓名和年龄的字典,如下所示:
people = [{'name': 'John', 'age': 25},{'name': 'Jane', 'age': 22},{'name': 'Peter', 'age': 30},{'name': 'Jenifer', 'age': 28}]
并且你想通过姓名来搜索一个人。
如果列表中包含这个人,你想显示这个人的信息。否则,你想显示一条消息,说明未找到该姓名。
为此,你可能会编写一个像这样的程序:
people = [{'name': 'John', 'age': 25},{'name': 'Jane', 'age': 22},{'name': 'Peter', 'age': 30},{'name': 'Jenifer', 'age': 28}]name = 'Maria'found = False
for person in people:if person['name'] == name:found = Trueprint(person)breakif not found:print(f'{name} not found!')
输出:
Maria not found!
工作原理:
- 首先,初始化一个变量,存储要搜索的人的姓名(Maria)。
- 然后,设置一个标志(
found)为False。如果输入的姓名与列表中的某个人匹配,则将其值设置为True,显示该人的信息,并使用break语句退出循环。 - 最后,检查
found标志并显示一条消息。
然而,如果你使用 for...else 语句,程序将会简洁得多。
以下展示了使用 for...else 语句的新版本程序:
people = [{'name': 'John', 'age': 25},{'name': 'Jane', 'age': 22},{'name': 'Peter', 'age': 30},{'name': 'Jenifer', 'age': 28}]name = 'Maria'for person in people:if person['name'] == name:print(person)break
else:print(f'{name} not found!')
通过使用 for...else 语句,程序无需在循环后使用标志和一个 if 语句。
在这个新程序中,如果输入的姓名与列表中的某个人匹配,程序将显示该人的信息,并使用 break 语句退出循环。
当循环遇到 break 语句时,else 子句将不会执行。
遍历空列表
以下示例使用 for...else 语句遍历一个列表,并显示该列表为空:
people = []for person in people:print(person)
else:print("The list is empty.")
输出:
The list is empty.
总结
- 使用 Python 的
for...else语句,可以在循环未遇到break语句或可迭代对象为空时执行一个代码块。
while…else
摘要:在本教程中,你将学习 Python 的 while else 语句以及如何有效地使用它。
Python while else 语句介绍
在 Python 中,while 语句可以有一个可选的 else 子句:
while condition:# code block to run
else:# else clause code block
在此语法中,条件会在每次迭代开始时进行检查。只要条件为 True,while 语句中的代码块就会执行。
当条件变为 False 且循环正常结束时,else 子句将会执行。然而,如果循环因 break 或 return 语句而提前终止,则 else 子句根本不会执行。
以下流程图说明了 while...else 子句:

如果你熟悉其他编程语言,比如 JavaScript、Java 或 C#,你可能会觉得在循环的上下文中使用 else 子句相当奇怪。
然而,while...else 子句在某些情况下实际上非常有用。让我们来看一个使用 while...else 语句的示例。
Python while…else 语句示例
假设我们有以下水果列表,其中每个水果都是一个包含 fruit_name 和 qty 键的字典:
basket = [{'fruit': 'apple', 'qty': 20},{'fruit': 'banana', 'qty': 30},{'fruit': 'orange', 'qty': 10}
]
我们希望编写一个程序,允许用户输入水果名称。根据输入的名称,我们将从水果篮列表中搜索该水果,如果水果在列表中,则显示其数量。
如果未找到该水果,我们将允许用户输入该水果的数量并将其添加到列表中。
以下是第一次尝试编写的程序:
basket = [{'fruit': 'apple', 'qty': 20},{'fruit': 'banana', 'qty': 30},{'fruit': 'orange', 'qty': 10}
]fruit = input('Enter a fruit:')index = 0
found_it = Falsewhile index < len(basket):item = basket[index]# check the fruit nameif item['fruit'] == fruit:found_it = Trueprint(f"The basket has {item['qty']} {item['fruit']}(s)")breakindex += 1if not found_it:qty = int(input(f'Enter the qty for {fruit}:'))basket.append({'fruit': fruit, 'qty': qty})print(basket)
需要注意的是,有更好的方法来开发这个程序。本示例中的程序仅用于演示目的。
工作原理:
- 首先,使用
input()函数提示用户输入。 - 其次,将索引初始化为零,并将
found_it标志初始化为False。索引将用于通过索引访问列表。如果找到了水果名称,则将found_it标志设置为True。 - 第三,遍历列表并检查水果名称是否与输入名称匹配。如果是,则将
found_it标志设置为True,显示水果的数量,并使用break语句退出循环。 - 最后,在循环后检查
found_it标志,如果found_it为False,则将新水果添加到列表中。
以下是在输入为 “apple” 时运行程序的结果:
Enter a fruit:apple
The basket has 20 apple(s)
以下是当输入为“lemon”(柠檬)时运行程序的结果:
Enter a fruit:lemon
Enter the qty for lemon:15
[{'fruit': 'apple', 'qty': 20}, {'fruit': 'banana', 'qty': 30}, {'fruit': 'orange', 'qty': 10}, {'fruit': 'lemon', 'qty': 15}]
该程序按预期工作。
然而,如果改用 while else 语句,代码将会更加简洁。
以下是使用 while else 语句的新版本程序:
basket = [{'fruit': 'apple', 'qty': 20},{'fruit': 'banana', 'qty': 30},{'fruit': 'orange', 'qty': 10}
]fruit = input('Enter a fruit:')index = 0while index < len(basket):item = basket[index]# check the fruit nameif item['fruit'] == fruit:print(f"The basket has {item['qty']} {item['fruit']}(s)")found_it = Truebreakindex += 1
else:qty = int(input(f'Enter the qty for {fruit}:'))basket.append({'fruit': fruit, 'qty': qty})print(basket)
在这个程序中,else 子句取代了使用 found_it 标志和循环后 if 语句的需求。
如果未找到水果,while 循环将正常终止,并且 else 子句将被执行以将新水果添加到列表中。
然而,如果找到了水果,while 循环将遇到 break 语句并提前终止。在这种情况下,else 子句将不会被执行。
总结
- 在
while else语句中,当while循环的条件为False且循环正常运行而未遇到break或return语句时,else子句将被执行。 - 当你需要在
while循环中使用标志时,可以尝试使用 Python 的while else语句。
Python模拟do…while语句
摘要:在本节中,你将学习如何在 Python 中模拟 do…while 循环语句
do…while 循环语句简介
如果你来自其他编程语言(如 JavaScript、Java 或 C#)的背景,那么你已经熟悉 do...while 循环语句。
与 while 循环不同,do...while 循环语句至少会执行一次迭代。它在每次迭代的末尾检查条件,并在条件为 False 之前一直执行代码块。
以下是 Python 中 do...while 循环的伪代码:
do# code block
while condition
不幸的是,Python 不支持 do...while 循环。不过,你可以使用 while 循环和 break 语句来模拟 do...while 循环语句。
首先,在 while 循环中将条件指定为 True,如下所示:
while True:# code block
这样可以让代码块至少执行一次。然而,由于条件始终为 True,这会导致一个无限循环。这不是我们期望的结果。
其次,放置一个条件以跳出 while 循环:
while True:# code block# break out of the loopif conditionbreak
在这个语法(结构)中,代码块在第一次时总是至少会执行一次,并且在每次迭代的末尾都会检查条件。
do…while 循环模拟示例
假设你需要开发一个数字猜谜游戏,其逻辑如下:
- 首先,在某个范围内(例如 0 到 10)生成一个随机数。
- 然后,反复提示用户输入一个数字。如果输入的数字比随机数低或高,就向用户提供提示。如果输入的数字等于随机数,则循环停止。
以下程序使用 while 循环来开发这个数字猜谜游戏:
from random import randint# determine the range
MIN = 0
MAX = 10# generate a secret number
secret_number = randint(MIN, MAX)# initialize the attempt
attempt = 0# The first attempt
input_number = int(input(f'Enter a number between {MIN} and {MAX}:'))
attempt += 1if input_number > secret_number:print('It should be smaller.')
elif input_number < secret_number:print('It should be bigger.')
else:print(f'Bingo! {attempt} attempt(s)')# From the second attempt
while input_number != secret_number:input_number = int(input(f'Enter a number between {MIN} and {MAX}:'))attempt += 1if input_number > secret_number:print('It should be smaller.')elif input_number < secret_number:print('It should be bigger.')else:print(f'Bingo! {attempt} attempt(s)')
以下是示例运行结果:
Enter a number between 0 and 10:5
It should be bigger.
Enter a number between 0 and 10:7
It should be bigger.
Enter a number between 0 and 10:8
Bingo! 3 attempt(s)
由于 while 循环在每次迭代开始时检查条件,因此有必要将提示用户输入和检查数字的代码重复两次,一次在循环之前,一次在循环内部。
为了避免这种重复代码,你可以使用 while 循环来模拟 do while 循环,如下所示:
from random import randint# determine the range
MIN = 0
MAX = 10# generate a secret number
secret_number = randint(MIN, MAX)# initialize the attempt
attempt = 0while True:attempt += 1input_number = int(input(f'Enter a number between {MIN} and {MAX}:'))if input_number > secret_number:print('It should be smaller.')elif input_number < secret_number:print('It should be bigger.')else:print(f'Bingo! {attempt} attempt(s)')break
其工作原理如下:
- 首先,移除
while循环之前的代码。 - 其次,通过使用
break语句添加条件,如果输入的数字等于随机数,则停止循环。
总结
- Python 不支持
do-while循环语句。 - 使用
while循环和break语句在 Python 中模拟do...while循环。
