14.2. Function Return

return

Python keyword for specifying value outcome from a function.

14.2.1. Syntax

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

14.2.2. Return Keyword

  • return keyword indicates outcome of the function

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

14.2.3. Code After Return

  • Code after return will not execute

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

14.2.4. Multiple Returns

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():
...     return 'hello'
...     return 'world'
>>>
>>> hello()
'hello'

14.2.5. Branching

>>> def hello():
...     if True:
...         return 'hello'
...     else:
...         return 'world'
>>>
>>> hello()
'hello'

14.2.6. Return Basic Type

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

14.2.7. Return Sequence

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

14.2.8. Return Mapping

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

14.2.9. 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())},
...     ]

14.2.10. 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"""

14.2.11. Retrieve Returned Value

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

14.2.12. Locals

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

14.2.13. Use Case - 0x01

>>> def age_category():
...     age = 30
...     if age < 18:
...         return 'junior'
...     else:
...         return 'senior'
>>> age_category()
'senior'

14.2.14. Assignments

Code 14.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
"""

# Define function `result`
# Function should return sum of `1` and `2`
# Define `result` with result of function call

Code 14.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')
"""

# Define function `result`
# Function should return a tuple: 'hello', 'world'
...

Code 14.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}
"""

# Define function `result`
# Inside function define variable `a: int` with value 1
# Inside function define variable `b: int` with value 2
# Return `dict[str,int]` with variable names and its values,
# for example: {'a': 1, 'b': 2}
# Do not use `locals()`
...

Code 14.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}
"""

# Define function `result`
# Inside function define variable `a: int` with value 1
# Inside function define variable `b: int` with value 2
# Return `dict[str,int]` with variable names and its values,
# for example: {'a': 1, 'b': 2}
# Use `locals()`
...


Code 14.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 = ...