Table of Contents
Introduction
The loop control statements are used to interrupt the normal execution of the sequence. Python supports below control statements:
Types | Description |
break | It is used to terminate the further loop execution and transfers the control to the immediate next statement following the loop. |
continue | It skips the further execution of the statements of the loop body and resets its condition. |
pass | It is used where code is required syntactically, but execution is not required. |
Example
1. Break statement
n = 10 for val in range(0, n): if val == 5 or val == 10: break print(val)
Output:
0
1
2
3
4
2. Continue statement
n = 10 for val in range(0, n): if val == 5: continue print("Example of continue control statement!")
Output:
Example of continue control statement!
3. Pass statement
for val in 'gocoding': pass print('Last letter',val)
Output:
Last letter g
Using Control Statements within Loops
Control Statements are statements that break the natural execution flow of a loop in Python. To be able to understand the importance and use of these control statements, first we need to have a fundamental idea of loops where these statements are used. Read more about Loops here.
Loop Control Statements
Loop controls statements are statements that are used to disrupt the normal flow or execution of the loop. Python supports several loop control statements as follows:
Continue Statement
The continue statement is used when you want the current iteration to end and the execution of the loop to move to the next iteration.
#Python program to demonstrate how to use the continue statement
for letter in ‘helloworld’:
if letter == ‘h’ or letter == ‘s’:
continue
print ‘Current Letter :’, letter
var = 10
OUTPUT
Current Letter : e
Current Letter : l
Current Letter : l
Current Letter : o
Current Letter : w
Current Letter : o
Current Letter : r
Current Letter : l
Current Letter : d
Break Statement
Break Statements are used when you want to break out of the loop at any point during the execution of the loop. In simpler words, the break statement terminates the execution of the loop.
for letter in ‘helloworld’:
if letter == ‘h’ or letter == ‘s’:
break
print ‘Current Letter :’, letter
OUTPUT
Current Letter : h
Pass Statement
When you want to leave the body of the loop empty, then you can simply write pass. The pass statement can also be used to fill in empty functions as well as classes.
#Python program to demonstrate pass statement
for letter in ‘helloworld’:
pass
print ‘Last Letter :’, letter
OUTPUT
Last Letter : d
0 Comments