In this example, you will learn about break and continue statements.
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.
Working with loops, Sometimes we need to terminate loop before complete execution on certain condition then break statement comes in light.
Python Break statement stops loop containing it and move next line after loop.
Example : Python Break Statement
# Program to use break statement
str = "codewolfy"
for x in str:
if x == "w":
break
print(x)
Output :
c
o
d
e
Here we loop through each character in codewolfy and whenever loop reaches w then it will stop execution from there.
The continue statement skips rest of code inside loop for current iteration only. This condition doesn't apply second time.
Python Break statement stops loop containing it and move next line after loop.
Example : Python Break Statement
# Program to use break statement
str = "codewolfy"
for x in str:
if x == "w":
continue
print(x)
Output :
c
o
d
e
o
l
f
y
Unlike the break, continue statement stops or skip only iteration of loop.
Ask anything about this examples