两个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什么都不做。计算不受影响。但是继续返回到循环的顶部继续进行下一个计算。

其他回答

for循环中pass和continue的区别:

那么为什么要传入python呢?

如果你想创建一个空类,方法或块。

例子:

class MyException(Exception):
    pass


try:
   1/0
 except:
   pass

在上面的例子中没有'pass'将抛出IndentationError。

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将继续处理。

如果pass位于循环的末尾,则差异可以忽略不计,因为流无论如何都会返回到循环的顶部。