如何使用函数跳出for循环?
我正在使用 for 循环对元素列表的函数中定义的 if 操作运行。第一个动作中有一个次要动作。我希望 for 循环在第一次操作成功后停止。下面是示例代码来演示:
my_list = [99, 101, 200, 5, 10, 20, 40]
def action(x):
if x >= 100:
print('It is finished')
over_100 = True
return over_100
def action2(x):
x += 1
action(x)
over_100 = False
for number in my_list:
action2(number)
if over_100:
break
我希望 for 循环在 >=100 的第一个实例处停止。例如,它应该将 1 加到 99(列表的第一个元素),然后停止所有内容。相反,它打印“它已完成”3 次,因为它遍历整个列表。
回答
您可以使函数返回一个值并检查循环中的值。您可以使用break来跳出循环。
list_of_scopes = [scope1, scope2, scope3, etc.)
def action_function():
return 'TEST' in xxxxx
for scope in list_of_scopes:
found = action_function()
if found:
break
由于Python 3.8你甚至可以用海象运营商,这使得更多的可读的代码:
for scope in list_of_scopes:
if found := action_function():
# optionally do something with `found`
break