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.
| Statement | What it does |
|---|---|
break | Stops the loop completely |
continue | Skips the rest of this round and goes to the next round |
pass | Does 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")
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..")
1
2
3
4
5
This statement will print 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)
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")
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")
Found 11
If no number was bigger than 10, the loop would finish by itself and print “Not found”.
Summary
breakstops the loop.continueskips to the next round.passis an empty placeholder.elseon a loop runs only if the loop did not hitbreak.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |