两个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
我应该注意的?
当前回答
可以这样考虑:
通过:Python只处理缩进!不像其他语言,这里没有空花括号。
因此,如果你想在条件为真时什么都不做,除了pass没有其他选择。
Continue:这只在循环的情况下有用。在这种情况下,对于一定范围的值,您不想在特定传递的条件为真之后执行循环的剩余语句,那么您将必须使用continue。
其他回答
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什么都不做。计算不受影响。但是继续返回到循环的顶部继续进行下一个计算。
是的,这是有区别的。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
是的,这是有区别的。Continue实际上跳过了当前循环迭代的其余部分(返回到开始)。Pass是一个空语句,不执行任何操作。
查看python文档
Pass只是表示空什么都不做,如下所示:
for i in range(3):
if i == 1:
pass
print(i)
输出:
0
1
2
Continue跳过当前循环进入下一个循环,如下所示:
for i in range(3):
if i == 1:
continue
print(i)
输出:
0
2
在您的示例中,没有区别,因为两个语句都出现在循环的末尾。Pass只是一个占位符,因为它什么都不做(它将执行传递给下一个语句)。另一方面,Continue有一个明确的目的:它告诉循环继续,就像它刚刚重新启动一样。
for element in some_list:
if not element:
pass
print element
和
for element in some_list:
if not element:
continue
print element