Open In App

Python return statement

Last Updated : 10 Dec, 2024
Comments
Improve
Suggest changes
58 Likes
Like
Report

A return statement is used to end the execution of the function call and it “returns” the value of the expression following the return keyword to the caller. The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned. A return statement is overall used to invoke a function so that the passed statements can be executed.

Example:


Output
5
True

Explanation:

  • add(a, b) Function: Takes two arguments a and b. Returns the sum of a and b.
  • is_true(a) Function: Takes one argument a. Returns the boolean value of a.
  • Function Calls: res = add(2, 3) computes the sum of 2 and 3, storing the result (5) in res. res = is_true(2 < 5) evaluates the expression 2 < 5 (which is True) and stores the boolean value True in res.

Let’s explore python return statement in detail:

Syntax:

def function_name(parameters):

# Function body

return value

When the return statement is executed, the function terminates and the specified value is returned to the caller. If no value is specified, the function returns None by default.

Note:

Note: Return statement can not be used outside the function.

Returning Multiple Values

Python allows you to return multiple values from a function by returning them as a tuple:

Example:


Output
Alice
30

In this example, the fun() function returns two values: name and age. The caller unpacks these values into separate variables.

Returning List

We can also return more complex data structures such as lists or dictionaries from a function:


Output
[9, 27]

In this case, the function fun() returns a list containing the square and cube of the input number.

Function returning another function

In Python, functions are first-class citizens, meaning you can return a function from another function. This is useful for creating higher-order functions.

Here’s an example of a function that returns another function:


Output
Message: Hello, World!


Next Article
Article Tags :
Practice Tags :

Similar Reads