- How does return() in Python work?
- Table of contents
- return() in Python
- Syntax of return() in Python:
- Using a return() statement for returning multiple values in Python
- Input:
- Output:
- return() in Python with an argument
- Input:
- Output:
- Function returning another function in Python
- Input:
- Output:
- Closing thoughts
- Что делает return в Python?
- Пример
- Вывод
- Пример оператора return Python
- Каждая функция что-то возвращает
- Что произойдет, если в операторе ничего нет?
- Может иметь несколько операторов
- Функция может возвращать несколько типов значений
- Возврат нескольких значений в одном операторе
- С блоком finally
- 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
How does return() in Python work?
In order to get a value from a function in any programming language, we use the return() statement. Likewise, in Python, the return() statement is used to exit a function and returns a value from a function. In this tutorial, we will read about various ways to use the return() statements in Python.
Table of contents
- Introduction to return() statement
- Returning Multiple Values in Python
- Argument in return() function
- Function returning another function
- Closing thoughts
return() in Python
The return() statement, like in other programming languages ends the function call and returns the result to the caller. It is a key component in any function or method in a code which includes the return keyword and the value that is to be returned after that.
Some points to remember while using return():
- The statements after the return() statement are not executed.
- return() statement can not be used outside the function.
- If the return() statement is without any expression, then the NONE value is returned.
Syntax of return() in Python:
def func_name(): statements. return [expression]
Using a return() statement for returning multiple values in Python
Python also gives an option to return multiple values from a function and in order to do that the user just needs to add multiple return values separated by commas. Also known as a tuple, can be created with or without using the ().
Input:
def statFun(a, b): difference = a-b percent_diff = (difference/a)*100 return difference, percent_diff; difference, percent_diff = statFun() print (difference) print (percent_diff)
Here, the function statFun() gives to values and by using tuple we return both of the values.
Output:
return() in Python with an argument
In Python, arguments can be used with a return statement. To begin with, arguments are the parameter given by the user and as we know, the argument is the value(s) as input, which is given by the user to the function.
Input:
def divNum(a, b): if b != 0 return a/b; else: return 0; print (divNum(4, 2)) print (divNum(2, 0))
Here, the function divNum() accepts two arguments and if the second argument is non zero it divides them otherwise returns 0.
Output:
Function returning another function in Python
As we know functions are treated as first-class objects in Python, therefore we can return a function from another function. A first-class object is an object that can be assigned to a variable, passed as an argument to a function, or used as a return value in a function.
A function that takes a function as an argument, returns a function as a result, or both is known as a higher-order function.
Input:
def func_1(a): def func_2(b): return a-b return func_2 x = func_1(100) print ("The value of a-b is", x(50)) def another_func(a): return a*10 def func(): return another_func y = func() print ("\nThe value of a*b is" y(10))
Output:
The value of a-b is 50 The value of a*b is 100
Closing thoughts
The return statement sends any object from the function back to the caller code. Since the return statement is a key part of any function or method, if you learn how to use it correctly, you can move to complex codes. One can learn about more Python concepts here.
Что делает return в Python?
Функция print() записывает, то есть «печатает», строку или число на консоли. Оператор return не выводит значение, которое возвращается при вызове функции. Это, однако, приводит к немедленному завершению или завершению функции, даже если это не последний оператор функции.
Во многих других языках функция, которая не возвращает значение, называется процедурой.
В данном коде значение, возвращаемое (то есть 2) при вызове функции foo(), используется в функции bar(). Эти возвращаемые значения печатаются на консоли только тогда, когда используются операторы печати, как показано ниже.
Пример
def foo(): print("Hello from within foo") return 2 def bar(): return 10*foo() print foo() print bar()
Вывод
Hello from within foo 2 Hello from within foo 20
Мы видим, что когда foo() вызывается из bar(), 2 не записывается в консоль. Вместо этого он используется для вычисления значения, возвращаемого из bar().
Пример оператора return Python
Давайте посмотрим на простой пример сложения двух чисел и возврата суммы вызывающему абоненту.
def add(x, y): total = x + y return total
Мы можем оптимизировать функцию, указав выражение в операторе возврата.
Каждая функция что-то возвращает
Давайте посмотрим, что возвращается, когда функция не имеет оператора возврата.
>>> def foo(): . pass . >>> >>> print(foo()) None >>>
Что произойдет, если в операторе ничего нет?
Когда оператор return не имеет значения, функция возвращает None.
>>> def return_none(): . return . >>> print(return_none()) None >>>
Может иметь несколько операторов
def type_of_int(i): if i % 2 == 0: return 'even' else: return 'odd'
Функция может возвращать несколько типов значений
В отличие от других языков программирования, функции Python не ограничиваются возвратом значений одного типа. Если вы посмотрите на определение функции, в нем нет никакой информации о том, что она может вернуть.
Давайте посмотрим на пример, в котором функция возвращает несколько типов значений.
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
Возврат нескольких значений в одном операторе
Мы можем вернуть несколько значений из одного оператора возврата. Эти значения разделяются запятой и возвращаются вызывающей программе в виде кортежа.
def return_multiple_values(): return 1, 2, 3 print(return_multiple_values()) print(type(return_multiple_values()))
С блоком finally
Как работает оператор return внутри блока try-except? Сначала выполняется код блока finally перед возвратом значения вызывающей стороне.
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
Если в блоке finally есть оператор return, то предыдущий оператор return игнорируется и возвращается значение из блока finally.
def hello(): try: return 'hello try' finally: print('finally block') return 'hello from finally' print(hello())
finally block hello from finally
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.