Sunday, July 5, 2015

Difference between pass, continue and break in python

pass vs continue vs break in python 

In Python, Pass, Continue and break are used to loops.

Though continue and break are similar to that of other traditional programming languages, pass is a unique feature available in python.

break   - Terminates the loop, after its invocation.
continue- Skips the current loop, and continues perform the next consecutive loops.
pass      - Does nothing. No logic to work. No break nor skipping a loop. pass is placed when there is no logic to be written for that condition, within the loop. It is advantageous for the developers for writing the logic in future.

The following example illustrates their difference:

1:  #!usr/bin/env python  
2:  print "\nExample to illustrate CONTINUE \n"  
3:  for j in range(10):  
4:    if j==5:  
5:      continue  
6:    print j,  
7:  print "\nExample to illustrate BREAK \n"  
8:  for p in range(10):  
9:    if p==5:  
10:      break  
11:    print p,  
12:  print "\nExample to illustrate PASS \n"  
13:  for i in range(10):  
14:    if i==5:  
15:      pass  
16:    print i,  



Example to illustrate CONTINUE

0 1 2 3 4 6 7 8 9
Example to illustrate BREAK

0 1 2 3 4
Example to illustrate PASS

0 1 2 3 4 5 6 7 8 9

Inference: Ex1 skipped printing 5 due to the presence of  continue.
                Ex2 stopped printing from 5 due to the presence of break.
                Ex3  printed all the values, with neither skipping a value nor stopping the loop.