The pass statement
The pass statement in Python usually serves as a placeholder to ensure that the block has at least one statement. It is a null operation, which means that nothing happens when it executes. In some cases, however, it can be used instead of the continue statement, since it allows the completion of the code inside the if statement in which it appears.
Consider the following example:
for i in range(1,11): if i==5: pass print('Number 5 encountered.') print(i)
The output:
>>> 1 2 3 4 Number 5 encountered. 5 6 7 8 9 10 >>>
Notice how the Number 5 encountered message was printed. If continue was used instead of the pass statement, the print statement inside the if statement would not execute.
Another example:
x = 0 for currentLetter in 'Hello world!': if currentLetter == 'l': pass x += 1 print('This is the',x,'instance of the letter l.') print('The current letter is', currentLetter) print('There have been',x,'instances of letter l.')
The code above calculates how many times the letter l appears in the Hello world! string and produces the following output:
>>> The current letter is H The current letter is e This is the 1 instance of the letter l. The current letter is l This is the 2 instance of the letter l. The current letter is l The current letter is o The current letter is The current letter is w The current letter is o The current letter is r This is the 3 instance of the letter l. The current letter is l The current letter is d The current letter is ! There have been 3 instances of letter l. >>>