if pass and if continue in python

87,316

Solution 1

Using continue passes for the next iteration of the for loop
Using pass just does nothing
So when using continue the print won't happen (because the code continued to next iteration)
And when using pass it will just end the if peacefully (doing nothing actually) and do the print as well

Solution 2

'0' not printed because of the condition "if not element:"

If the element is None, False, empty string('') or 0 then , loop will continue with next iteration.

Solution 3

if not element:

In both examples, this will only match the 0.

pass

This does nothing. So the next command, print element, will be executed.

continue

This tells Python to stop this for loop cycle and skip to the next cycle of the loop. So print element will never be reached. Instead, the for loop will take the next value, 1 and start from the top.

Solution 4

There is a fundamental difference between pass and continue in Python. pass simply does nothing, while continue jumps to the next iteration of the for loop. The statement if not 0 always evaluates to True, so both pass and continue statements will be executed. pass will do nothing and print the value, while continue will skip to the next iteration ignoring the print statement written below.

Solution 5

From: https://docs.python.org/2/tutorial/controlflow.html#pass-statements

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.

In your code snippet above if not element will evaluate to true when element = 0. In python 0 is same as boolean false. In the first loop pass does nothing, so it prints all three elements. In the second loop, continue will stop the execution of the rest of loop for that iteration. so the print statement never executes. so it only prints 1 and 2.

Share:
87,316
Shelly
Author by

Shelly

Updated on November 02, 2020

Comments

  • Shelly
    Shelly over 3 years

    I saw someone posted the following answer to tell the difference between if x: pass and if x: continue.

    >>> 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
    

    What is the result for if not element when a = 0? Why when using continue, 0 is not printed?