Return keyword in python

Python return Statement

The statement after the return statement is not executed. If the return statement is without any expression, then None is returned.

Please note that the return statement in Python can not be used outside the function.

How to use return statement in Python?

To use a return statement in Python, use the syntax return [expression]. The return statement is important because it allows you to return values from functions and methods.

Syntax

def method(): statements . . return [expression]

Example

def club(): return 11 + 19 print(club())

We have defined a function that returns the sum of two values in this example. This example returns one value.

How to return multiple values in Python

To return multiple values in Python from a function, we can use the following ways.

  1. Return multiple values by separated commas(tuple)
  2. Return list
  3. Return set
  4. Return dictionary

Return various values by separating commas

To return multiple values by separated commas, use the return statement. In Python, you can return multiple values separated by commas. The returned values are tuples with comma-separated values.

def club(): return 11, 19, 21, 46 print(club())

From the output, you can see that the function has returned a tuple containing command-separated values.

Читайте также:  Loops and arrays in java

In Python, comma-separated values are considered tuples without parentheses, except where required by syntax.

We can also verify its data type.

def club(): return 11, 19, 21, 46 print(type(club()))

You can access the item by its index.

def club(): return 11, 19, 21, 46 data = club() print(data[2])

If you try to access the index that does not exist, it will throw an exception.

def club(): return 11, 19, 21, 46 data = club() print(data[20])
Traceback (most recent call last): File "app.py", line 5, in print(data[20]) IndexError: tuple index out of range

We have got the IndexError: tuple index out of range.

How to return a list in Python

To return a list in Python, use the return keyword and write the list you want to return inside the function. The list is like the array of elements created using square brackets.

Lists are different from arrays as they can contain elements of various types. In addition, lists in Python are other than tuples as they are mutable.

def club(): str = "AppDividend" x = 20 return [str, x] data = club() print(data)

In this code, we can see that we have a return list with the help of [ ].

Using [ ] returns a list instead of a tuple.

How to return a dictionary in Python

To return a Dictionary in Python, use the return keyword and write the dictionary you want to return inside the function. The dictionary is similar to a hash or map in other languages.

We can define a dictionary using a dict() method and then specify the key according to values, and we will compose the Dictionary and return the Dictionary.

def club(): dct = dict() dct['str'] = "AppDividend" dct['age'] = 3 return dct data = club() print(data)

We initialized an empty dictionary first and then appended the key-value pairs to the Dictionary. And then return the Dictionary.

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Что делает 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

Что произойдет, если в операторе ничего нет?

Когда оператор 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()))

Python Возвращает Несколько Значений

С блоком 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

Источник

Оцените статью