The return statement

The return statement

In Python, the return statement is used to exit a function and return a value to the caller. When a return statement is encountered in a function, the function stops executing and control is returned to the point where the function was called. If a value is specified after the return keyword, that value is returned to the caller as the result of the function.

For example, consider the following function that calculates the square of a number and returns the result:

python

def square(x):

    return x ** 2

In this function, the return statement is used to return the result of the calculation to the caller.

The return statement can also be used without a value to exit a function early. In this case, the function does not return a value, and the value of the expression following the return keyword is None by default.

For example, consider the following function that prints the elements of a list up to a specified index:

python

def print_list_items(lst, stop_index):

    for i in range(stop_index):

        print(lst[i])

        if i == len(lst) – 1:

            return

In this function, the return statement is used to exit the function early if the index stop_index is greater than the length of the list 1st. If the index is greater than the length of the list, the loop will continue to iterate over the list until the end is reached, but the function will exit before any more elements are printed. It’s important to note that a function can have multiple return statements. When a return statement is encountered, the function will stop executing and control will be returned to the point where the function was called, regardless of whether there are more return statements later in the function.

Apply for Python Certification!

https://www.vskills.in/certification/certified-python-developer

Back to Tutorials

Share this post
[social_warfare]
Varargs and keyword only parameters
Docstrings and annotations

Get industry recognized certification – Contact us

keyboard_arrow_up