What is the use of break and continue in Python?
In Python, break and continue statements can alter the flow of a normal loop.
Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.
The break and continue statements are used in these cases.
Python break statement
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.
Syntax of break
break
#example of break in while loop
i=1 while(i<=10): if(i>5): break print(i) i=i+1
Output:
1
2
3
4
5
>>>
#example of break in for loop
n=list(range(1,11)) for i in n: if(i>5): break print(i)
Output:
1
2
3
4
5
>>>
Python continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue
continue
#example of continue in for loop
#to print only odd nos
n=list(range(1,11)) for i in n: if(i%2==0): continue print(i)
Output:
1
3
5
7
9
>>>
#to print only even nos
n=list(range(1,11)) for i in n: if(i%2==1): continue print(i)
Output:
2
4
6
8
10
>>>
#example of continue in while loop
#to print only odd nos
i=1 while(i<=10): if(i%2==0): i=i+1 continue print(i) i=i+1
Output:
1
3
5
7
9
>>>
#to print only even nos
i=1 while(i<=10): if(i%2==1): i=i+1 continue print(i) i=i+1
Output:
2
4
6
8
10
>>>
What is pass statement in Python?
In Python programming, pass is a null statement. The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when pass is executed. It results into no operation (NOP).
Syntax of pass
pass
We generally use it as a placeholder.
Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. The interpreter would complain. So, we use the pass statement to construct a body that does nothing.
Example: pass Statement
# pass is just a placeholder for
# functionality to be added later.
n = {‘h’, ‘e’, ‘l’, ‘l’,’o’}
for val in n:
pass
We can do the same thing in an empty function or class as well.
def function(args):
pass
class example:
pass