Jump statements are used to alter the flow of a program by jumping to a different part of the code. The main jump statements in Python are break
, continue
, and return
. Let’s go through each of them with examples.
break
Statement
The break
statement is used to exit a loop prematurely when a certain condition is met.
# Using break in a for loop
for number in range(1, 10):
if number == 5:
break
print(number)
Output:
1
2
3
4
In this example, the loop will terminate when number
equals 5, so it will only print numbers 1 through 4.
continue
Statement
The continue
statement skips the rest of the code inside the loop for the current iteration and jumps back to the beginning for the next iteration.
Example:
# Using continue in a for loop
for number in range(1, 10):
if number == 5:
continue
print(number)
1
2
3
4
6
7
8
9
In this example, when number
is 5, the continue
statement skips the print statement and moves to the next iteration, so 5 is not printed.
return
Statement
The return
statement is used to exit a function and optionally pass back an expression or value to the caller.
Example:
def find_first_even(numbers):
for number in numbers:
if number % 2 == 0:
return number
return None
result = find_first_even([1, 3, 7, 10, 11])
print(result)
Output:
10
In this example, the function find_first_even
will return the first even number it finds in the list. Once it finds 10, it exits the function immediately with the return
statement.
Combining break
and continue
You can also combine these statements within the same loop to control the flow more precisely.
Example:
# Combining break and continue
for number in range(1, 10):
if number % 2 == 0:
continue
if number > 7:
break
print(number)
Output:
1
3
5
7
In this example, even numbers are skipped because of the continue
statement and the loop stops completely when number
exceeds 7 due to the break
statement.