In this tutorial, we will learn about the break, continue and pass statements in Python. These statements are also known as loop control statements and can alter the normal flow of a loop.
Python Break Statement
Suppose you have an assignment to find a specific number in a given range. When your code finds that number, you want to exit from the loop, instead of continuing till the end. To exit from the loop you have to use break keyword in your program.
You can use break keyword in a while or for loop in Python. Whenever a break keyword is found in code, it immediately exits from that block.
Example 1: Example of a break statement in Python.
# It will print only 1 2 n=0 while n<=10: n=n+1 if n==3: break print(n)
Python Continue Statement
Like a break keyword, a continue statement is also used within loops. Whenever a continue statement is found in code, control moves to the beginning of the loop, skip the current iteration and start the next iteration.
Example 2: Example of a continue statement in Python.
#It will print 1 2 4 5 without 3 n=0 while n<5: n=n+1 if n==3: continue print(n)
Pass Statement in Python
In Python, the pass keyword is used for nothing. It means when you want to execute nothing as code you can write pass in loop, function or if as a statement. The pass statement is generally ignored by the Python interpreter and can act as a null statement.
Example 3: Example of the pass keyword in Python.
#print odd numbers only for i in range(1,10): if i%2==0: pass else: print(i)