- Python return statement
- Python Function without return statement
- Python Return Statement Example
- Python return statement with expression
- Python return boolean
- Python return string
- Python return tuple
- Python function returning another function
- Python function returning outer function
- Python return multiple values
- Summary
- Python return Statement
- Understanding the Python return Statement in Functions
- Syntax of Python return Statement
- Python return Statement Example
- Every Function in Python returns Something
- Python return Statement without any Value
- Python Functions can have Multiple return Statements
- Python Functions return Multiple Types of Values
- Returning Multiple Values from a Function in a Single return Statement
- Python return Statement with finally block
- Summary
Python return statement
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
The python return statement is used to return values from the function. We can use the return statement in a function only. It can’t be used outside of a Python function.
Python Function without return statement
Every function in Python returns something. If the function doesn’t have any return statement, then it returns None .
def print_something(s): print('Printing::', s) output = print_something('Hi') print(f'A function without return statement returns ')
Output:
Python Return Statement Example
We can perform some operation in a function and return the result to the caller using the return statement.
def add(x, y): result = x + y return result output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return statement with expression
We can have expressions also in the return statement. In that case, the expression is evaluated and the result is returned.
def add(x, y): return x + y output = add(5, 4) print(f'Output of add(5, 4) function is ')
Output:
Python return boolean
Let’s look at an example where we will return the boolean value of the argument of a function. We will use bool() function to get the boolean value of the object.
def bool_value(x): return bool(x) print(f'Boolean value returned by bool_value(False) is ') print(f'Boolean value returned by bool_value(True) is ') print(f'Boolean value returned by bool_value("Python") is ')
Output:
Python return string
Let’s look at an example where our function will return the string representation of the argument. We can use the str() function to get the string representation of an object.
def str_value(s): return str(s) print(f'String value returned by str_value(False) is ') print(f'String value returned by str_value(True) is ') print(f'String value returned by str_value(10) is ')
Output:
Python return tuple
Sometimes we want to convert a number of variables into a tuple. Let’s see how to write a function to return a tuple from a variable number of arguments.
def create_tuple(*args): my_list = [] for arg in args: my_list.append(arg * 10) return tuple(my_list) t = create_tuple(1, 2, 3) print(f'Tuple returned by create_tuple(1,2,3) is ')
Output: Further Reading: Python *args and **kwargs
Python function returning another function
We can return a function also from the return statement. This is similar to Currying, which is the technique of translating the evaluation of a function that takes multiple arguments into evaluating a sequence of functions, each with a single argument.
def get_cuboid_volume(h): def volume(l, b): return l * b * h return volume volume_height_10 = get_cuboid_volume(10) cuboid_volume = volume_height_10(5, 4) print(f'Cuboid(5, 4, 10) volume is ') cuboid_volume = volume_height_10(2, 4) print(f'Cuboid(2, 4, 10) volume is ')
Output:
Python function returning outer function
def outer(x): return x * 10 def my_func(): return outer output_function = my_func() print(type(output_function)) output = output_function(5) print(f'Output is ')
Output:
Python return multiple values
If you want to return multiple values from a function, you can return tuple, list, or dictionary object as per your requirement. However, if you have to return a huge number of values then using sequence is too much resource hogging operation. We can use yield, in this case, to return multiple values one by one.
def multiply_by_five(*args): for arg in args: yield arg * 5 a = multiply_by_five(4, 5, 6, 8) print(a) # showing the values for i in a: print(i)
Output:
Summary
The python return statement is used to return the output from a function. We learned that we can also return a function from another function. Also, expressions are evaluated and then the result is returned from the function. You can checkout complete python script and more Python examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Python return Statement
In Python, the return statement exits a function and returns the specified value to the caller. Multiple return statements may exist in a function, but only the one that fulfils the specified condition first is executed.
The return keyword is one of the built-in keywords in Python which is also used for increasing readability and writing clear code in Python.
This tutorial will cover all the fundamental things you should know about return statements in Python.
Understanding the Python return Statement in Functions
- The Python return statement is used in a function to return something to the caller program.
- We can use the return statement inside a function only.
- In Python, every function returns something. If there are no return statements, then it returns None.
- If the return statement contains an expression, it’s evaluated first and then the value is returned.
- The return statement terminates the function execution.
- A function can have multiple return statements. When any of them is executed, the function terminates.
- A function can return multiple types of values.
- Python functions can return multiple values in a single return statement.
Syntax of Python return Statement
The syntax is straightforward, it consists of the keyword return followed by an expression.
Here the expression can be anything like an expression that can be evaluated to a value, the actual value, or even a function that we want to return to the caller.
Python return Statement Example
Let’s look at a simple example of a function that takes two numbers to perform a calculation and return the total to the caller.
def add(x, y): total = x + y return total
We can optimize the function by having the expression in the return statement.
Let’s do a function call by passing two arguments, then print the result we got.
result = add(5, 3) print(result)
See, here we got the sum, meaning the function successfully returned the total value.
Every Function in Python returns Something
Let’s see what is returned when a function doesn’t have a return statement.
>>> def foo(): . pass . >>> >>> print(foo()) None >>>
We got “None”, so if we didn’t pass a return statement and try to access the function value, by default it returns None.
Python return Statement without any Value
When the return statement has no value, the function returns None.
>>> def return_none(): . return . >>> print(return_none()) None >>>
So, either you have used a return statement with no value, or there is no return statement, and the function returns None.
Python Functions can have Multiple return Statements
A function can have multiple returns, the one that satisfies the condition will be executed first and the function will exit.
def type_of_int(i): if i % 2 == 0: return 'even' else: return 'odd' result = type_of_int(7) print(result)
Python Functions return Multiple Types of Values
Unlike other programming languages, Python functions are not restricted to returning a single type of value. If you look at the function definition, it doesn’t have any information about what it can return.
Let’s look at an example where the function will return numbers of values having multiple types.
def get_demo_data(object_type): if 'str' == object_type: return 'test' elif 'tuple' == object_type: return (1, 2, 3) elif 'list' == object_type: return [1, 2, 3] elif 'dict' == object_type: return else: return None print(get_demo_data('str')) # Output: 'test' print(get_demo_data('tuple')) # Output: (1, 2, 3) print(get_demo_data('list')) # Output: [1, 2, 3] print(get_demo_data('dict')) # Output: print(get_demo_data('set')) # Output: None
Returning Multiple Values from a Function in a Single return Statement
A function can have multiple return values in a single statement. These values are separated by a comma and returned to the caller program as a tuple.
def return_multiple_values(): return 1, 2, 3 print(return_multiple_values()) print(type(return_multiple_values()))
Python return Statement with finally block
When the return statement is executed inside a try-except block, the finally block code is executed first before returning the value to the caller.
def hello(): try: return 'hello try' finally: print('finally block') def hello_new(): try: raise TypeError except TypeError as te: return 'hello except' finally: print('finally block') print(hello()) print(hello_new())
finally block hello try finally block hello except
If the finally block has a return statement, then the earlier return statement gets ignored and the value from the finally block is returned.
def hello(): try: return 'hello try' finally: print('finally block') return 'hello from finally' print(hello())
finally block hello from finally
Summary
A return value in a function is the value that it sends back to the caller after it is finished executing. In other words, we can say that the return statement is the last statement that a function or method executes before it terminates. We can even return a function from another function. A function without a return statement or a return statement without a value returns None by default.
The return statement is certainly not an essential aspect of writing valuable functions because the main purpose of creating a function is to encapsulate a block of code in order to reuse that code. But it is the most important part of creating a function as it makes the function more feature-full and readable, so the next time you are creating a function, try using return instead of using the print statement.