两个Python关键字continue和pass之间有什么显著的区别吗
for element in some_list:
if not element:
pass
and
for element in some_list:
if not element:
continue
我应该注意的?
两个Python关键字continue和pass之间有什么显著的区别吗
for element in some_list:
if not element:
pass
and
for element in some_list:
if not element:
continue
我应该注意的?
当前回答
是的,他们做的事情完全不同。Pass只是什么都不做,而continue则继续进行下一次循环迭代。在您的示例中,如果在if之后添加另一条语句,区别就会很明显:在执行pass之后,将执行这条进一步的语句。在继续之后,它就不会了。
>>> a = [0, 1, 2]
>>> for element in a:
... if not element:
... pass
... print(element)
...
0
1
2
>>> for element in a:
... if not element:
... continue
... print(element)
...
1
2
其他回答
它们之间有区别,continue跳过循环的当前迭代并执行下一个迭代。Pass什么都不做。它是一个空语句占位符。 我想给你们举个例子,能更好地说明这一点。
>>> some_list = [0, 1, 2]
... for element in some_list:
... if element == 1:
... print "Pass executed"
... pass
... print element
...
0
Pass executed
1
2
... for element in some_list:
... if element == 1:
... print "Continue executed"
... continue
... print element
...
0
Continue executed
2
是的,这是有区别的。Continue实际上跳过了当前循环迭代的其余部分(返回到开始)。Pass是一个空语句,不执行任何操作。
查看python文档
x = [1,2,3,4]
for i in x:
if i==2:
pass #Pass actually does nothing. It continues to execute statements below it.
print "This statement is from pass."
for i in x:
if i==2:
continue #Continue gets back to top of the loop.And statements below continue are executed.
print "This statement is from continue."
输出为
>>> This statement is from pass.
同样,让我们运行相同的代码,只做了一些小更改。
x = [1,2,3,4]
for i in x:
if i==2:
pass #Pass actually does nothing. It continues to execute statements below it.
print "This statement is from pass."
for i in x:
if i==2:
continue #Continue gets back to top of the loop.And statements below continue are executed.
print "This statement is from continue."
输出为-
>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.
Pass什么都不做。计算不受影响。但是继续返回到循环的顶部继续进行下一个计算。
可以这样考虑:
通过:Python只处理缩进!不像其他语言,这里没有空花括号。
因此,如果你想在条件为真时什么都不做,除了pass没有其他选择。
Continue:这只在循环的情况下有用。在这种情况下,对于一定范围的值,您不想在特定传递的条件为真之后执行循环的剩余语句,那么您将必须使用continue。
是的,这是有区别的。Continue强制循环在下一次迭代时开始,而pass意味着“这里没有代码要执行”,并将继续遍历循环体的剩余部分。
运行这些,看看有什么不同:
for element in some_list:
if not element:
pass
print(1) # will print after pass
for element in some_list:
if not element:
continue
print(1) # will not print after continue