Loop Control Statements
Loop Control Statements
The Loop control statements change the execution from its normal sequence.
Python supports the following loop control statements for both for and while loops
Control Statement |
Description |
break |
It terminates the loop when the condition is not satisfied and shifts the control to the immediate statement of that loop. |
continue |
It executes until the condition satisfies and ignores the remaining statements and again starts the execution from beginning onwards. |
pass |
It is null operation. Nothing will happen when it executes. |
for loop using break statement
Ex 1: Sample example of for loop using break statement
Output
0
1 2 3 |
Ex 2: The following program describes the use of break in a for loop iterating over a list. User gives a number as an input, and it is searched in the list. If it is found, then the loop terminates with the ‘found’ message otherwise displays a message “Not found”.
Output
Number is: 10
Not found |
Ex 3: The below code depicts the use of break statement inside a loop
Output
s
t r The end |
If the string has repeated letters
Output
P
y t h o n P r o g r a EnD |
for loop using continue statement
Ex 1: A sample program on for loop using continue Statement
Output
0
1 2 3 5 6 7 8 9 |
Ex 2: The following program shows the use of continue statement inside loops.
Output
S
u d h k r The end |
Ex 3 The below code depicts the use of continue statement inside a loop
Output
P
y t h o n P r o g r a i n g EnD |
for loop using pass statement
Ex 1: A sample program on for loop using pass statement
Output:
This is pass block Current letter: P This is pass block Current letter: y This is pass block Current letter: t This is pass block Current letter: h This is pass block Current letter: o This is pass block Current letter: n BYe |
Ex 2: Another snippet for pass statement
Output:
{‘P’, ‘y’, ‘h’, ‘n’, ‘o’, ‘t’} |
Note:
When you execute the above code you will be displayed by random arrangement of a specific word. You can observe the same in the term “Python” with unordered arrangement.
Ex 3: The below code depicts the use of pass statement inside a loop
Output
P
y t h o n P r o g r a m m i n g EnD |
While loop using break statement
Ex 1: To print the numbers in reverse order.
Output
10
9 8 7 6 |
Ex 2: The below code take input from the user and prints until the vowel is entered.
Output
Enter a vowel: t
Not a vowel. Enter a vowel: f Not a vowel. Enter a vowel: o Hey!!It’s vowel |
while using continue statement
Ex 1: a sample example on While using continue statement
Output
9
8 7 6 4 3 2 1 0 End |
Ex 2: To print all even numbers less than 10 and greater than or equal to 0.
Output
8 6 4 2 0 |
while using pass statement
Ex 1: To print 1 to 10 numbers in the following two different ways using pass statement.
Output
1
2 3 4 5 7 8 9 10 |
Ex 2: To interrupt the flow with printing any string.
Output
1
2 3 4 5 Hello 7 8 9 10 |