What is the difference between pass and continue in python

My test shows that both pass and continue can be used equivalently to create an empty for -loop for testing purposes. Is there any difference between the two?

+7
python for-loop
source share
6 answers

The pass keyword is the no-op keyword. He does not do anything. It is often used as a placeholder for code to be added later:

 if response == "yes": pass # process "yes" case 

On the other hand, the continue keyword is used to restart the loop at the breakpoint, for example:

 for i in range(10): if i % 2 == 0: continue print i 

This loop will only output odd numbers, since continue returns to the loop control statement ( for ) for iterations, where i is equal.

In terms of an empty for loop, you are correct that they are functionally identical. You can use any of:

 for i in range(10): pass for i in range(10): continue 
+7
source share

pass does nothing (no operation), and continue makes the control flow continue the next cycle of the loop.

+3
source share

If the loop contains only one statement, pass or continue will not make any difference. But if there are several operators, then this is important:

 for item in my_list: pass print(item) #This will be executed for item in my_list: continue print(item) #won't be executed 

Basically, the pass statement does nothing, while the continue statement restarts the loop.

But in your case:

 for item in my_list: pass #Since there nothing after pass, the loop is finished. for item in my_list: continue #You're restarting the loop 

There the difference is not very noticeable.

Hope this helps!

+2
source share

continue means skip to end of loop body. If it is a while , the loop proceeds to the loop test; if it is a for loop, the loop advances to the next element of what it iterates.

pass does nothing. It exists because you must have something in the body of an empty block statement, and pass more readable than executing 1 or None as an instruction for this purpose.

+2
source share

This will lead to an infinite loop if you use continue :

 i = 0 while i<1: continue i = i + 1 print i 

because continue only goes to the next iteration. But pass will work for this case.

+1
source share

pass and continue work, but can create infinite loops.

For example, the following code will create an infinite loop.

 i = 0 while i<100: continue # replacing continue with pass still creates an infinite loop. 

If you want to avoid this (perhaps you intend to modify the i withe loop, but you haven't written the code yet), use break .

+1
source share

All Articles