To break out of a function in Python, we can use the return statement. The Python return statement can be very useful for controlling the flow of data in our Python code.

def doStuff():
    print("Here before the return")
    return
    print("This won't print")

doStuff()

#Output:
Here before the return

When working with functions in Python, it can be useful to need to break out of a function early based on various conditions.

Functions terminate when we return a value back, and so to break out of a function in Python, we can use the return statement. In this case, we will return nothing.

Below is an example of how to get out of a function early with a return statement.

def doStuff():
    print("Here before the return")
    return
    print("This won't print")

doStuff()

#Output:
Here before the return

As you can see, the second print statement doesn’t print because we broke out of the function early.

How to Use the Python break Statement to Break Out of For Loop

Another useful control flow statement in Python is the break statement. We can use break statements to break out of loops in our Python code.

To break out of a loop based on a condition, you can just put “break” in an if statement.

Below is an example of how to break out of a for loop in Python with the Python break statement.

def printLetters(string):
    for i in range(0,len(string)):
        if i == 2:
            break
        print(string[i])

printLetters("Word")

#Output:
W
o

Hopefully this article has been useful for you to learn how to break out of functions in Python with a return statement.

Categorized in:

Python,

Last Update: February 26, 2024