Difference between break continue and pass in Python

Introduction

For more information about for loops in Python, you can find the full article here. So what is the difference between break, continue and pass in Python ? let us borrow some relevant sections from the previous article…

Break statement

Python like other languages provides a special purpose statement called break. This statement terminates the loop immediately and control is returned to the statement right after the body of the loop. As we mentioned earlier, an infinite loop can be used on purpose as in computer games. To quit the game, a break statement is used to terminate the infinite game loop. Another example, imagine you are searching for an element in a long array. If you find that element near the beginning of the list, there is no point to continue the search to the end of the list.

Here is an example

If you execute the code above, you will notice that all numbers are printed except 8 and 9 because the loop was terminated when we found 7

Continue statement

This statement is used to skip the remaining code in the body of the loop and continue iteration. You can always use if statements to implement the same logic but using continue is nice for code clarity and readability.

Here is an example

If you execute the code above it will only print the odd numbers 1, 3, 5

Python pass statement

This is like a no operation statement or do nothing. As before, this language feature is a convenience and can always be replaced with an equivalent code of ours. It is useful when the code goes into an unimplemented functionality (ex. stubs).

Here is an example:

In the code above, we are detecting even numbers and want to process them however the code to process them is not implemented yet.

That is all for today. Thanks for visiting.

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *