Python 中继续语句的使用示例?

continue声明的 定义是:

continue语句继续循环的下一次迭代。

我找不到任何好的代码示例。

有没有人可以提出一些简单的情况下,continue是必要的?

209292 次浏览

通常情况下,继续是必要的/有用的,是您想要跳过循环中剩余的代码并继续迭代的情况。

我并不真的认为这是必要的,因为您总是可以使用 if 语句来提供相同的逻辑,但是它可能有助于提高代码的可读性。

例如,如果您想根据变量的值执行不同的操作:

my_var = 1
for items in range(0,100):
if my_var < 10:
continue
elif my_var == 10:
print("hit")
elif my_var > 10:
print("passed")
my_var = my_var + 1

在上面的例子中,如果我使用 break,解释器将跳过循环。但是使用 continueit 只会跳过 if-elif 语句,直接进入循环的下一项。

def filter_out_colors(elements):
colors = ['red', 'green']
result = []
for element in elements:
if element in colors:
continue # skip the element
# You can do whatever here
result.append(element)
return result


>>> filter_out_colors(['lemon', 'orange', 'red', 'pear'])
['lemon', 'orange', 'pear']

我喜欢在有许多条件需要满足的循环中使用 keep,然后再开始“下一步工作”。所以代替这样的代码:

for x, y in zip(a, b):
if x > y:
z = calculate_z(x, y)
if y - z < x:
y = min(y, z)
if x ** 2 - y ** 2 > 0:
lots()
of()
code()
here()

我得到的代码是这样的:

for x, y in zip(a, b):
if x <= y:
continue
z = calculate_z(x, y)
if y - z >= x:
continue
y = min(y, z)
if x ** 2 - y ** 2 <= 0:
continue
lots()
of()
code()
here()

通过这样做,我避免了非常深的嵌套代码。此外,通过首先消除最频繁发生的情况,很容易优化循环,这样我只需要处理不常见但重要的情况(例如,除数为0) ,而没有其他的显示阻塞。

import random


for i in range(20):
x = random.randint(-5,5)
if x == 0: continue
print 1/x

是一个非常重要的控制语句。上面的代码表示一个典型的应用程序,其中可以避免除以零的结果。我经常使用它时,我需要存储从程序的输出,但不想存储输出,如果程序已经崩溃。注意,为了测试上面的例子,将最后一条语句替换为 print 1/float (x) ,否则只要有一个分数,就会得到零,因为 randint 返回一个整数。为了清楚起见,我省略了。

这里有一个简单的例子:

for letter in 'Django':
if letter == 'D':
continue
print("Current Letter: " + letter)

产出将包括:

Current Letter: j
Current Letter: a
Current Letter: n
Current Letter: g
Current Letter: o

它跳过当前迭代的其余部分(这里是 print) ,继续到循环的下一个迭代。

假设我们要打印所有不是3和5的倍数的数字

for x in range(0, 101):
if x % 3 ==0 or x % 5 == 0:
continue
#no more code is executed, we go to the next number
print x

有些人评论可读性,说: “哦,它对可读性没有多大帮助,谁在乎呢?”

假设您需要在主代码之前进行检查:

if precondition_fails(message): continue


''' main code here '''

注意,你可以做到这一点 之后的主要代码写不改变该代码在任何情况下。如果您对代码进行了区分,那么由于主代码没有间距更改,所以只会突出显示添加了“ keep”的行。

想象一下,如果您必须对生产代码进行一个断点修复,结果只是添加一行带继续的代码。当您查看代码时,很容易看到这是唯一的更改。如果开始用 If/else 包装主代码,diff 将突出显示新缩进的代码,除非忽略间距更改,这在 Python 中尤其危险。我认为,除非您遇到过必须在短时间内推出代码的情况,否则您可能不会完全理解这一点。

它不是绝对必要的,因为它可以使用 IF 完成,但是它更具可读性,并且在运行时花费更少。

我使用它是为了在数据不满足某些要求时跳过循环中的迭代:

# List of times at which git commits were done.
# Formatted in hour, minutes in tuples.
# Note the last one has some fantasy.
commit_times = [(8,20), (9,30), (11, 45), (15, 50), (17, 45), (27, 132)]


for time in commit_times:
hour = time[0]
minutes = time[1]


# If the hour is not between 0 and 24
# and the minutes not between 0 and 59 then we know something is wrong.
# Then we don't want to use this value,
# we skip directly to the next iteration in the loop.
if not (0 <= hour <= 24 and 0 <= minutes <= 59):
continue


# From here you know the time format in the tuples is reliable.
# Apply some logic based on time.
print("Someone commited at {h}:{m}".format(h=hour, m=minutes))

产出:

Someone commited at 8:20
Someone commited at 9:30
Someone commited at 11:45
Someone commited at 15:50
Someone commited at 17:45

如您所见,在 continue语句之后没有出现错误的值。

这里有一个非常好的关于继续和中断语句的可视化表示

Continue example

来源