14.2. Function Return

return

Python keyword for specifying value outcome from a function.

Syntax:

def myfunction():
    return <expression>

Example:

>>> def run():
...     return 1

14.2.1. Return Keyword

  • return keyword indicates outcome of the function

>>> def run():
...     return 1
>>>
>>>
>>> run()
1

14.2.2. Code After Return

  • Code after return will not execute

>>> def run():
...     print('before')
...     return 1
...     print('after')
>>>
>>> run()
before
1

14.2.3. Multiple Returns

  • There could be multiple return keywords in a function

  • Code after first return will not execute

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 run():
...     return 1
...     return 2
>>>
>>> run()
1

14.2.4. Branching

>>> def run():
...     if ...:
...         return 1
...     else:
...         return 2
>>>
>>> run()
1

14.2.5. Return Basic Type

>>> def run():
...     return 1
>>> def run():
...     return 2.0
>>> def run():
...     return True
>>> def run():
...     return 'hello'

14.2.6. Return Sequence

>>> def run():
...     return [1, 2.0, True, 'hello']
>>> def run():
...     return (1, 2.0, True, 'hello')
>>> def run():
...     return 1, 2.0, True, 'hello'
>>> def run():
...     return {1, 2.0, True, 'hello'}

14.2.7. Return Mapping

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

14.2.8. Return Nested Sequence

>>> def run():
...     return [
...         ('Mark', 'Melissa', 'Rick'),
...         ['Mark', 'Melissa', 'Rick'],
...         {'Mark', 'Melissa', 'Rick'},
...         {'name': 'Mark Watney', 'groups': ('users', 'staff')},
...         {'name': 'Melissa Lewis', 'groups': ['users', 'staff']},
...         {'name': 'Rick Martinez', 'groups': {'users', 'staff'}},
...     ]

14.2.9. Return None

  • Function will return None if no explicit return is specified

>>> def run():
...     return None
>>> def run():
...     pass
>>> def run():
...     print('hello')
>>> def run():
...     """
...     This is a docstring for my function.
...     Docstrings serves as a documentation.
...     It is considered a good practice to
...     always write a docstring for your functions.
...     """

14.2.10. Retrieve Returned Value

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

14.2.11. Use Case - 1

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

14.2.12. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return Int
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Modify function `one()`
# 2. Function should return value `1`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `one()`
# 2. Funkcja powinna zwracać wartość `1`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

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

>>> one()
1
"""

# Function should return value `1`
# type: Callable[[], int]
def one():
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return None
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Modify function `empty()`
# 2. Function should return value `None`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `empty()`
# 2. Funkcja powinna zwracać wartość `None`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

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

>>> print(empty())
None
"""

# Function should return value `None`
# type: Callable[[], None]
def empty():
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return Expression
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Modify function `add()`
# 2. Function should return sum of `1` and `2`
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `add()`
# 2. Funkcja powinna zwracać sumę `1` i `2`
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

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

>>> add()
3
"""

# Function should return sum of `1` and `2`
# type: Callable[[], int]
def add():
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return Tuple
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Modify function `get_user()`
# 2. Function should return a tuple: 'Mark', 'Watney'
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `get_user`
# 2. Funkcja powinna zwracać krotkę: 'Mark', 'Watney'
# 3. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

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

>>> get_user()
('Mark', 'Watney')
"""

# Function should return a tuple: 'Mark', 'Watney'
# type: Callable[[], tuple[str,str]]
def get_user():
    ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return Dict
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Modify function `get_data()`
# 2. Function should return a dict:
#    {'firstname': 'Mark', 'lastname': 'Watney'}
# 3. Do not use built-in function `locals()`
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zmodyfikuj funkcję `get_data`
# 2. Funkcja powinna zwracać dict:
#    {'firstname': 'Mark', 'lastname': 'Watney'}
# 3. Nie używaj wbudowanej funkcji `locals()`
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

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

>>> get_data()
{'firstname': 'Mark', 'lastname': 'Watney'}
"""

# Function should return a dict:
# {'firstname': 'Mark', 'lastname': 'Watney'}
def get_data():
    firstname = 'Mark'
    lastname = 'Watney'
    return ...


# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Function Return Capture
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% English
# 1. Define `result` with result of `add` 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
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from inspect import isfunction

>>> assert isfunction(add), \
'Object `add` 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 add():
    return 1 + 2


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