What is the difference between break and pass in Python? And about the function Continue?
In this article we’ll learn the difference between break and pass in Python, also, how we use the continue function. When should we use each of these instructions?
Hey you programmer, what’s up? Let’s learn more about Python!
The two magic words: break and continue are used in loops (repeating structures)
And the pass method is used in functions or other occasions where we don’t have the code completely defined, let’s now see each of them in detail.
How to use break
The idea of break is to interrupt a repeating structure, as a for as an example, when it is interpreted by the program, so we can tie this to logic, see an example:
list = [1,2,3,4,5,6,7,8,9,10] for i in list: if(i == 5): break else: print(i)
Here the list will print up to number 4, after that, it enters the if of break and the loop is ejected
So that’s what break is for
How to use continue
The continue method skips an execution when the instruction is interpreted
That is, instead of stopping the loop completely, it will run the next iteration
Let’s look at an example:
list = [1,2,3,4,5,6,7,8,9,10] for i in list: if(i % 2 == 0): continue else: print(i)
Here we are running the continue on the even values of the list, so this example will only print the odd values
The output will be:
1 2 3 4 1 3 5 7 9
How to use the pass
The pass must be used when we want a code to be valid, but we do not intend to implement it yet.
That is, it fills a void and lets the code ‘pass’
Check out the example:
def someFunction(): pass
Notice that you can run the code without getting any interpreter errors
That doesn’t happen if a function is created empty
But it doesn’t stop there, the pass can be used in other functions that the return is uncertain, for example a try with except
In this article we learned the difference between break and pass in Python, as well as continue
We also learned possible implementations of these instructions
Break and continue are used in loops.
The pass can have several use cases, especially when we don’t intend to implement some code yet and we need something to fill it out.
Do you want to learn more about Python? Click here!