两个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
我应该注意的?
当前回答
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什么都不做。计算不受影响。但是继续返回到循环的顶部继续进行下一个计算。
其他回答
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则继续进行下一次循环迭代。在您的示例中,如果在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
在您的示例中,没有区别,因为两个语句都出现在循环的末尾。Pass只是一个占位符,因为它什么都不做(它将执行传递给下一个语句)。另一方面,Continue有一个明确的目的:它告诉循环继续,就像它刚刚重新启动一样。
for element in some_list:
if not element:
pass
print element
和
for element in some_list:
if not element:
continue
print element
Pass只是继续循环或条件。它什么都不做。不过,Continue用于跳过当前迭代,并进入下一个迭代。
你可能会问,如果不需要,为什么要使用pass呢?考虑以下情况:
text = "I am a coder."
if text == "I am not a coder.":
print("Programming is interesting! You should try it out!")
elif text == "I am a coder.":
pass
Pass只是一个语法占位符,用来填充一些空间。如果在检查出特定条件时不想做任何事情,可以使用pass作为占位符。在Python中不能只编写空的条件、循环或函数。
是的,这是有区别的。Continue实际上跳过了当前循环迭代的其余部分(返回到开始)。Pass是一个空语句,不执行任何操作。
查看python文档