What is difference between break continue and return statements in Python?

In Python, “break”, “continue”, and “return” are used in loops to control the flow of code execution. and a lot of students create unnecessary confusion in their minds and you are one of those then this article is for you. In this article, I have explained it very simple way with an example. wanted to strengthen your concept just investing 4-5 minutes to read this? Go Ahead.

Break Statement

“break” is used to terminate a loop prematurely. It immediately exits the loop and continues with the next statement after the loop.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for num in numbers:
    if num == 5:
        break
    print(num)

Output:

1
2
3
4

In the above example, the loop iterates through the list of numbers, but it terminates as soon as it reaches the number 5. Therefore, the output only shows the numbers 1, 2, 3, and 4.

Continue Statement

 
“continue” is a keyword used inside loops (e.g. for loops or while loops) to skip the current iteration of the loop and move on to the next iteration.

Example:

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
for num in numbers:
    if num == 5:
        continue
    print(num)

Output:

1
2
3
4
6
7
8

In the above example, the loop iterates through the list of numbers, but it skips over the number 5 and moves on to the next iteration. Therefore, the output does not show the number 5.

Return Statement

The “return” statement is used to exit a function and return a value. When a return statement is executed, it immediately stops the execution of the function and sends a result back to the caller of the function.

Example:

def square(x):
    if x < 0:
        return None
    return x**2
print(square(5))
print(square(-5))

Output:

25
None

In the above example, the “square” function returns the square of a number, but it returns “None” if the input is negative. When the function returns “None”, it immediately exits the function and does not execute any code after the “return” statement.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top