11.2. Function Return

return

Python keyword for specifying value outcome from a function.

11.2.1. Syntax

def myfunction():
    return <expression>
>>> def mean():
...     return (1+2) / 2
>>> def add():
...     a = 1
...     b = 2
...     return a + b

11.2.2. Return Keyword

  • return keyword indicates outcome of the function

>>> def hello():
...     return 'hello'
>>>
>>>
>>> hello()
'hello'

Code after return will not execute:

>>> def hello():
...     print('before')
...     return 'hello'
...     print('after')
>>>
>>> hello()
before
'hello'

You can have more than one return keyword in a function, although function will close after hitting any of them, and will not proceed any further.

>>> def hello():
...     print('before')
...     return 'hello'
...     return 'world'
...     print('after')
>>>
>>> hello()
before
'hello'
>>> def hello():
...     print('before')
...     return 'hello'
...     print('between')
...     return 'world'
...     print('after')
>>>
>>> hello()
before
'hello'
>>> def hello():
...     if True:
...         return 'hello'
...     else:
...         return 'world'
>>>
>>> hello()
'hello'
>>> def hello():
...     if True:
...         return 'hello'
...     else:
...         return 'world'
...     print('after if')
>>>
>>> hello()
'hello'

11.2.3. Return Basic Type

>>> def myfunction():
...     return 42
>>> def myfunction():
...     return 13.37
>>> def myfunction():
...     return 'Mark Watney'
>>> def myfunction():
...     return True

11.2.4. Return Sequence

>>> def myfunction():
...     return list([42, 13.37, 'Mark Watney'])
>>> def myfunction():
...     return [42, 13.37, 'Mark Watney']
>>> def myfunction():
...     return tuple((42, 13.37, 'Mark Watney'))
>>> def myfunction():
...     return (42, 13.37, 'Mark Watney')
>>> def myfunction():
...     return 42, 13.37, 'Mark Watney'
>>> def myfunction():
...     return set({42, 13.37, 'Mark Watney'})
>>> def myfunction():
...     return {42, 13.37, 'Mark Watney'}

11.2.5. Return Mapping

>>> def myfunction():
...     return dict(firstname='Mark', lastname='Watney')
>>> def myfunction():
...     return {'firstname': 'Mark', 'lastname': 'Watney'}

11.2.6. Return Nested Sequence

>>> def myfunction():
...     return [
...         ('Mark', 'Watney'),
...         {'Mark Watney', 'Melissa Lewis', 'Rick Martinez'},
...         {'astro': 'Mark Watney', 'agency': {'name': 'NASA'}},
...         {'astro': 'Mark Watney', 'missions': ['Ares1', 'Ares3']},
...         {'astro': 'Mark Watney', 'medals': (list(), tuple(), set())},
...     ]

11.2.7. Return None

  • Python will return None if no explicit return is specified

>>> def myfunction():
...     return None
>>> def myfunction():
...     print('hello')
>>> def myfunction():
...     pass
>>> def myfunction():
...     """My function"""

11.2.8. Intercept Returned Value

>>> def myfunction():
...     return 1
>>>
>>>
>>> result = myfunction()
>>> print(result)
1

11.2.9. Locals

>>> def myfunc():
...     a = 1
...     b = 2
...     return locals()
...
>>> myfunc()
{'a': 1, 'b': 2}

11.2.10. Assignments

Code 11.3. Solution
"""
* Assignment: Function Return Expression
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Define function `result`
    2. Function should return sum of `1` and `2`
    3. Define `result` with result of function call
    4. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `result`
    2. Funkcja powinna zwracać sumę `1` i `2`
    3. Zdefiniuj `result` z wynikiem wywołania funkcji
    4. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert result is not Ellipsis, \
    'Write solution inside `result` function'
    >>> assert isfunction(result), \
    'Object `result` must be a function'

    >>> result()
    3
"""


Code 11.4. Solution
"""
* Assignment: Function Return Tuple
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Define function `result`
    2. Function should return a tuple: 'hello', 'world'
    3. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `result`
    2. Funkcja powinna zwracać krotkę: 'hello', 'world'
    3. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert result is not Ellipsis, \
    'Write solution inside `result` function'
    >>> assert isfunction(result), \
    'Object `result` must be a function'

    >>> result()
    ('hello', 'world')
"""


Code 11.5. Solution
"""
* Assignment: Function Return Dict
* Type: class assignment
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Define function `result`
    2. Inside function define variable `a: int` with value 1
    3. Inside function define variable `b: int` with value 2
    4. Return `dict[str,int]` with variable names and its values,
       for example: {'a': 1, 'b': 2}
    5. Do not use `locals()`
    6. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `result`
    2. Wewnątrz funkcji zdefiniuj zmienną `a: int` z wartością 1
    3. Wewnątrz funkcji zdefiniuj zmienną `b: int` z wartością 2
    4. Zwróć `dict[str,int]` z nazwami zmiennych i ich wartościami,
       przykład: {'a': 1, 'b': 2}
    5. Nie używaj `locals()`
    6. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert result is not Ellipsis, \
    'Write solution inside `result` function'
    >>> assert isfunction(result), \
    'Object `result` must be a function'

    >>> result()
    {'a': 1, 'b': 2}
"""


Code 11.6. Solution
"""
* Assignment: Function Return Locals
* Type: class assignment
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Define function `result`
    2. Inside function define variable `a: int` with value 1
    3. Inside function define variable `b: int` with value 2
    4. Return `dict[str,int]` with variable names and its values,
       for example: {'a': 1, 'b': 2}
    5. Use `locals()`
    6. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `result`
    2. Wewnątrz funkcji zdefiniuj zmienną `a: int` z wartością 1
    3. Wewnątrz funkcji zdefiniuj zmienną `b: int` z wartością 2
    4. Zwróć `dict[str,int]` z nazwami zmiennych i ich wartościami,
       przykład: {'a': 1, 'b': 2}
    5. Użyj `locals()`
    6. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert result is not Ellipsis, \
    'Write solution inside `result` function'
    >>> assert isfunction(result), \
    'Object `result` must be a function'

    >>> result()
    {'a': 1, 'b': 2}
"""


Code 11.7. Solution
"""
* Assignment: Function Return Capture
* Type: class assignment
* Complexity: easy
* Lines of code: 1 lines
* Time: 2 min

English:
    1. Define `result` with result of `compute` function call
    2. Run doctests - all must succeed

Polish:
    1. Zdefiniuj `result` z wynikiem wywołania funkcji `compute`
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

    >>> assert isfunction(compute), \
    'Object `compute` must be a function'
    >>> assert result is not Ellipsis, \
    'Assign result to variable: `result`'
    >>> assert type(result) is int, \
    'Variable `result` has invalid type, should be int'

    >>> result
    3
"""


def compute():
    return 1 + 2


# Result of `compute` function call
# type: int
result = ...