In the last two topics, you learned about loops which are used to repeat a certain process some number of times.
What if we can control the way our loop operates?
In Python, we can jump out of a loop or jump to the starting condition of a loop whenever we want. We do this with the help of break
and continue
statements respectively.
Python break
break
is used to break or terminate a loop whenever we want.
Just type break
after the statement after which you want to break the loop. As simple as that!
Python break Syntax
break
Python break Examples
for n in range(1, 10):
print("*")
if n == 2:
break
In the first iteration of the loop, '*' gets printed and the condition n == 2
is checked. Since the value of n
is 1, therefore the condition becomes False
In the second iteration of the loop, again '*' gets printed and the condition is checked. Since this time the condition of if is satisfied (because n
is 2), the break
statement terminates the loop.
Let’s write the same program using a while
loop.
n = 1
while n < 10:
print("*")
if n == 2:
break
n = n + 1
Let's have a look at one more example.
while True:
x = int(input("Enter 0 to stop"))
if x == 0:
break
This is an infinite loop. To terminate this, we are using break
. If the user enters 0, then the condition of if will get satisfied and the break
statement will terminate the loop.
Python continue
continue
statement works similar to the break
statement. The only difference is that break statement terminates the loop whereas continue statement skips the rest of the statements in the loop and starts the next iteration.
Python continue Syntax
continue
Python continue Examples
for n in range(1, 10):
if n == 5:
continue
print(n)
Notice that 5 is not printed in the output. This is because in the fifth iteration when the value of n
became 5, the if condition became True and the continue
statement in the body of the if statement got executed. Thus the next statement print(n)
didn’t get executed and the sixth iteration started.
The same program using while loop is shown below.
n = 1
while n < 10:
if n == 5:
n = n + 1
continue
print(n)
n = n + 1