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?
Difference between pass and continuecontinue forces the loop to start at the next iteration whereas pass means "there is no code to execute here" and will continue through the remainder of the loop body.
As you can see in the official documentation, the pass statement does nothing. In Python, the contents cannot be omitted in the def statement of the function definition and the if statement of the conditional branch. You can use the pass statement when you need to write something, but you don't need to do anything.
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.
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
'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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With