Python break, continue and pass

Python break, continue and pass



Hello Learners… In this session you will learn to use break, continue and pass statements to alter the flow of a loop.


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 the 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 the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

Syntax of break
1
break
Example: Python break
1
2
3
4
5
6
7
8
# Use of break statement inside the loop
 
for val in "string":
    if val == "i":
        break
    print(val)
 
print("The end")

Output

s
t
r
The end

In this program, we iterate through the “string” sequence. We check if the letter is i, upon which we break from the loop. Hence, we see in our output that all the letters up till i gets printed. After that, the loop terminates.

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
1
continue
Example: Python continue
1
2
3
4
5
6
7
8
# Program to show the use of continue statement inside loops
 
for val in "string":
    if val == "i":
        continue
    print(val)
 
print("The end")

Output

s
t
r
n
g
The end

This program is same as the above example except the break statement has been replaced with continue.

We continue with the loop, if the string is i, not executing the rest of the block. Hence, we see in our output that all the letters except i gets printed.

Python pass statement

The pass statement is used as a placeholder for future code.

When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed.

Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

Example: Python pass
1
2
3
sequence = {'p', 'a', 's', 's'}
for val in sequence:
    pass

Using the pass keyword in a function definition:

1
2
def myfunction:
  pass

Using the pass keyword in an if statement:

1
2
3
4
5
a = 33
b = 200
 
if b > a:
  pass

No comments:

Post a Comment