这是一个简单的例子:
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
),并继续进行下一次迭代。
我喜欢在有很多条件需要满足才能进入实质业务的循环中使用continue关键字。因此,代码不会像这样:
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)。
continue
与使用GOTO
类似。不过,这是使用GOTO
的正确方式。 - dotancohen通常需要/有用的情况下使用 continue,是当您想要跳过循环中的剩余代码并继续迭代时。
我并不真正相信它是必要的,因为您可以始终使用 if 语句提供相同的逻辑,但这可能有助于提高代码的可读性。
if <condition>: continue
而不是if not <condition>: ...
可以避免在没有它的情况下需要一层缩进。 - Dan D.continue
语句时,我们实际上是跳出了一个条件测试部分,并允许循环迭代继续进行到下一个迭代?我不明白这比使用else
更好在哪里。这只是关于改进可读性和运行时性能吗? - AKKOimport random
for i in range(20):
x = random.randint(-5,5)
if x == 0: continue
print 1/x
continue是一种非常重要的控制语句。以上代码展示了一个典型的应用场景,可以避免除以零的结果。当我需要存储程序输出,但不想在程序崩溃时存储输出时,我经常使用它。请注意,为了测试上面的示例,请将最后一条语句替换为print 1/float(x),否则每当有一个分数时,您将获得零,因为randint返回一个整数。为了清晰起见,我省略了它。
有些人评论说可读性并没有太大改善,"哦,谁在乎呢?"
假设你需要在主代码之前进行一项检查:
if precondition_fails(message): continue
''' main code here '''
请注意,您可以在主代码编写完成后以任何方式不改变该代码的情况下进行此操作。如果对代码进行差异比较,则只会突出显示添加了“continue”行,因为主代码中没有空格更改。
想象一下,如果您需要在生产代码上进行故障修复,结果只需要添加一个包含"continue"的行。当您审查代码时,很容易看到这是唯一的更改。如果您开始在主要代码周围添加if/else,除非忽略间距更改,否则diff将突出显示新缩进的代码,这在Python中尤其危险。我认为,除非您曾经处于必须在短时间内推出代码的情况下,否则您可能无法充分欣赏此功能。
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']
continue
语句起到了什么作用?如果使用 element not in colors
条件语句替代,代码可读性并不会降低。 - ekhumoro假设我们想打印所有不是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 x %3 == 0 or x % 5 == 0:
,pass
,else:
,print x
。 - Wildcardcontinue
。我的结论是从来不需要,但在某些情况下(比如这个例子),使用 continue
会使代码更易读。这是一个很好的例子。 - Wildcard这并非绝对必要,因为可以使用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
语句后没有被执行。if
只能做到continue
所做的事情。 continue
跳过即使在if
块之外的代码。 - brycmy_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
,解释器将跳过循环。但是使用continue
,它只会跳过if-elif语句并直接进入循环的下一项。my_var
的初始值为0,你的这个例子永远不会输出任何内容,因为第一个条件语句总是为真。 - Dan D.elif
应该改成if
。这段代码看起来似乎你并不知道自己在做什么。 - John Machin
continue
的作用,但并不是非常有用,当你可以这样做时:如果letter!= 'D':print'当前字母:',letter
- Chris_Rands