Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if pass and if continue in python

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?

like image 384
Shelly Avatar asked May 09 '16 20:05

Shelly


People also ask

Is Pass and continue same in Python?

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.

Can I use pass in if statement Python?

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.

Is pass the same as continue?

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.


3 Answers

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

like image 72
Neo Avatar answered Oct 01 '22 00:10

Neo


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

like image 23
Anoop Avatar answered Oct 01 '22 01:10

Anoop


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.

like image 21
C14L Avatar answered Oct 01 '22 02:10

C14L