Python Jump Statements

Jump statements change the normal flow of a loop. Python has three of them: break, continue and pass. You use them inside for and while loops.

StatementWhat it does
breakStops the loop completely
continueSkips the rest of this round and goes to the next round
passDoes nothing. It is a placeholder

break statement

The break statement ends the loop right away, usually when a condition becomes true.

for i in range(1, 11):
    if i == 5:
        break
    print(i)

print("Loop ended")
Output of the above program is

1
2
3
4
Loop ended

The same works in a while loop. In this example we print up to 5 and stop.

x = 1
while x <= 10:
    print(x)
    if x == 5:
        break
    x = x + 1

print("This statement will print after the loop..")
Output of the above program is

1
2
3
4
5
This statement will print after the loop..

Note: The break statement stops only the loop. The program continues with the code after the loop.

continue statement

The continue statement skips the remaining code of the current round, and starts the next round. Here we print only the odd numbers.

for i in range(1, 8):
    if i % 2 == 0:
        continue
    print(i)
Output of the above program is

1
3
5
7


pass statement

The pass statement does nothing. Python needs some code inside an if, loop, function or class, so use pass when you want to write it later.

for i in range(3):
    pass          # code will be written later

print("No error")
Output of the above program is

No error


else clause with loops

A loop can have an else block. It runs when the loop ends normally, which means without a break.

numbers = [3, 8, 11]

for n in numbers:
    if n > 10:
        print("Found", n)
        break
else:
    print("Not found")
Output of the above program is

Found 11

If no number was bigger than 10, the loop would finish by itself and print “Not found”.


Summary

  • break stops the loop.
  • continue skips to the next round.
  • pass is an empty placeholder.
  • else on a loop runs only if the loop did not hit break.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.