Break and Continue Statement in loop in Python
Break and Continue Statement in loop Python
The break Statement in for loop
With
the break statement we can stop the loop before
it has looped through all the items:
Example
Exit
the loop when x
is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x
== "banana":
break
Example
Exit
the loop when x
is "banana", but this time the break comes before
the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x
== "banana":
break
print(x)
The break Statement in while
loop
The break
keyword
is used to break out a for
loop,
or a while
loop.
Example
Break
out of a while loop:
i = 1
while i < 9:
print(i)
if i
== 3:
break
i += 1
Example
Exit
the loop when i is 3:
i = 1
while i < 6:
print(i)
if i
== 3:
break
i += 1
The continue Statement
With
the continue statement we can stop the current
iteration of the loop, and continue with the next:
Example
Do
not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x
== "banana":
continue
print(x)
Example
Continue
to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i
== 3:
continue
print(i)
Post a Comment