Working With Break, Continue, Pass and else Statements in Python
For
and while loop allows to repeat instruction until final result do not get. Some
times due to some external factors influence on program. In this situation loop
should be completely exit and skip part of loop before continue it. This is
controlled with break, continue and pass statements in Python.
1. Break Statement:
Break
statement helps to exit a loop when an external factors are triggered. The break statement is written within the
block of code under loop statement after if statement.
Syntax:
break
Example:
#breal
statement in while loop
string1="hello"
ch=0
while
ch<len(string1):
if string1[ch]=='o':
ch=ch+1
break
print(" Current letters:" ,string1[ch])
ch+=1
O/P:
Current letters: h
Current letters: e
Current letters: l
Current letters: l
Another Example:
A=10
while A>=1:
print(" A=", A)
A=A-1
if A==5:
break
print("Out of Loop")
O/P:
A=10
A=9
A=8
A=7
A=6
Out of Loop
The
continue statement in python is used to skip the rest of the code in the loop
for current iteration if external condition is triggered. The current iteration
of the loop is disrupted but program will return to the top of the loop.
This
statement is written within the block after the if condition.
Syntax:
continue
Example:
A=0
while A<10:
print(" A=", A)
A=A+1
if A>5:
continue
print("A=", A)
print("Out of Loop")
O/P:
A=1
A=2
A=3
A=4
A=5
Out of Loop
3. Pass Statement:
Pass
statement in python used with loops when an external condition is triggered.
Pass allows to handle this external trigger without the loop being impacted.
All the code will be continue to read unless a break or other statements are
occurs.
This
statement is also written like other statements within the code block under the
loop and after the if condition.
Syntax:
pass
Example:
A=0
while A<10:
print(" A=", A)
A=A+1
if A>5:
pass
print("A=",A)
print("Out of Loop")
O/P:
A=1
A=2
A=3
A=4
A=5
A=6
A=7
A=8
A=9
A=10
Out of Loop
4. else statement in Loop:
In
Python we can else statement in loops.
When
we use else statement in for loop the else loop is only executed when loop
exhausted iteration of the list.
And
when we use else statement in while loop the else statement is executed when
condition becomes false.
Syntax:
else:
Example:
for i in range(1,5):
print(i)
else:
print("No break")
O/P:
1
2
3
4
No break
Another Example:
for i in range(1,5):
print(i)
break
else:
print("No break")
O/P:
1
Only 1 will be displayed because condition becomes true and flow of control will break with the help of break statement.
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏