摘要:在本教程中,你将学习 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 = False
while index < len(basket):
item = basket[index]
# check the fruit name
if item['fruit'] == fruit:
found_it = True
print(f"The basket has {item['qty']} {item['fruit']}(s)")
break
index += 1
if 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 = 0
while index < len(basket):
item = basket[index]
# check the fruit name
if item['fruit'] == fruit:
print(f"The basket has {item['qty']} {item['fruit']}(s)")
found_it = True
break
index += 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
语句。