If pass and if continue in python

I saw someone post the following answer to tell the difference between if pass and if continue. I know that the list is "a" [0,1,2], I just don’t know what the result is for "if not element"? Why when using continue, 0 is not printed, only 1 and 2 are printed? when a = 0, "if not an element" is "if not 0", does it have special meaning?

>>> 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 
+5
source share
6 answers

'0' is not printed due to the condition "if not element:"

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

+4
source

Using continue for the next iteration for for loop
Using pass just does nothing; therefore, using continue print will not (because the code continued the next iteration)
And when using pass it will simply end if peacefully (without actually doing anything) and << 24> also

+3
source

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

The skip instruction does nothing. It can be used when the instruction is required syntactically, but the program does not require any action.

In your code snippet above, if not element will evaluate to true when element = 0 . In python 0 this is the 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 rest of the loop for this iteration. therefore, the print instruction is never executed. therefore it prints only 1 and 2.

+3
source

continue is a control flow statement used to exit the innermost body of an iteration. When your code hits

 if not element 

the interpreter skips all element values ​​that are not checked for true . 0 is one of these values, and it proceeds to the next iteration of the loop when it does not encounter the continue statement and therefore continues to print the value of element 1 and then 2

In contrast, the pass statement does nothing but skip and return to the next line of code to execute.

+1
source
 if not element: 

In both examples, this will only match 0 .

 pass 

It does nothing. So, the following print element command will be executed.

 continue 

This tells Python to end this loop cycle and move on to the next cycle loop. Therefore, the print element will never be reached. Instead, the for loop will take the next value 1 and start at the top.

0
source

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

0
source

All Articles