Is there a difference between `continue` and `pass` in a for loop in python?

前端 未结 11 1333
孤街浪徒
孤街浪徒 2020-11-27 09:05

Is there any significant difference between the two python keywords continue and pass like in the examples

for element in some_list         


        
相关标签:
11条回答
  • 2020-11-27 09:59

    In those examples, no. If the statement is not the very last in the loop then they have very different effects.

    0 讨论(0)
  • 2020-11-27 10:01

    continue will jump back to the top of the loop. pass will continue processing.

    if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.

    0 讨论(0)
  • 2020-11-27 10:02

    Yes, they do completely different things. pass simply does nothing, while continue goes on with the next loop iteration. In your example, the difference would become apparent if you added another statement after the if: After executing pass, this further statement would be executed. After continue, it wouldn't.

    >>> 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
    
    0 讨论(0)
  • 2020-11-27 10:02

    Yes, there is a difference. Continue actually skips the rest of the current iteration of the loop (returning to the beginning). Pass is a blank statement that does nothing.

    See the python docs

    0 讨论(0)
  • 2020-11-27 10:02

    pass could be used in scenarios when you need some empty functions, classes or loops for future implementations, and there's no requirement of executing any code.
    continue is used in scenarios when no when some condition has met within a loop and you need to skip the current iteration and move to the next one.

    0 讨论(0)
提交回复
热议问题