16.2. Function Return — Python
- return
Python keyword for specifying value outcome from a function.
Syntax:
def myfunction(): return <expression>
Example:
>>> def run(): ... return 1
16.2.1. Return Keyword
returnkeyword indicates outcome of the function
>>> def run(): ... return 1 >>> >>> >>> run() 1
16.2.2. Code After Return
Code after
returnwill not execute
>>> def run(): ... print('before') ... return 1 ... print('after') >>> >>> run() before 1
16.2.3. Multiple Returns
There could be multiple
returnkeywords in a functionCode after first
returnwill 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
16.2.4. Branching
>>> def run(): ... if ...: ... return 1 ... else: ... return 2 >>> >>> run() 1
16.2.5. Return Basic Type
>>> def run(): ... return 1
>>> def run(): ... return 2.0
>>> def run(): ... return True
>>> def run(): ... return 'hello'
16.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'}
16.2.7. Return Mapping
>>> def run(): ... return {'firstname': 'Alice', 'lastname': 'Apricot'}
16.2.8. Return Nested Sequence
>>> def run(): ... return [ ... ('alice', 'bob', 'carol'), ... ['alice', 'bob', 'carol'], ... {'alice', 'bob', 'carol'}, ... {'username': 'alice', 'groups': ('users', 'staff')}, ... {'username': 'bob', 'groups': ['users', 'staff']}, ... {'username': 'carol', 'groups': {'users', 'staff'}}, ... ]
16.2.9. Return None
Function will
return Noneif no explicit return is specified
>>> def run(): ... return None
>>> 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. ... """
16.2.10. Retrieve Returned Value
>>> def run(): ... return 1 >>> >>> >>> result = run() >>> print(result) 1
16.2.11. Use Case - 1
>>> def status(): ... age = 30 ... if age < 18: ... return 'junior' ... else: ... return 'senior'
16.2.12. Assignments
# %% About # - Name: Function Return Int # - Difficulty: easy # - Lines: 2 # - Minutes: 2 # %% 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 # %% 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ść # %% Expected # >>> one() # 1 # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert one is not Ellipsis, \ 'Variable `one` has an invalid value; assign result of your program to it.' >>> assert isfunction(one), \ 'Object `one` must be a function' >>> one() 1 """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types from typing import Callable one: Callable[[], int] # %% Data # %% Result def one(): ...
# %% About # - Name: Function Return None # - Difficulty: easy # - Lines: 2 # - Minutes: 2 # %% 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 # %% 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ść # %% Expected # >>> result = empty() # >>> print(result) # None # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert empty is not Ellipsis, \ 'Variable `empty` has an invalid value; assign result of your program to it.' >>> assert isfunction(empty), \ 'Object `empty` must be a function' >>> result = empty() >>> print(result) None """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types from typing import Callable empty: Callable[[], None] # %% Data # %% Result def empty(): ...
# %% About # - Name: Function Return Expression # - Difficulty: easy # - Lines: 2 # - Minutes: 2 # %% 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 # %% 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ść # %% Expected # >>> add() # 3 # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert add is not Ellipsis, \ 'Variable `add` has an invalid value; assign result of your program to it.' >>> assert isfunction(add), \ 'Object `add` must be a function' >>> add() 3 """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types from typing import Callable add: Callable[[], int] # %% Data # %% Result def add(): ...
# %% About # - Name: Function Return Tuple # - Difficulty: easy # - Lines: 2 # - Minutes: 2 # %% 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 # %% English # 1. Modify function `get_user()` # 2. Function should return a tuple: 'Alice', 'Apricot' # 3. Run doctests - all must succeed # %% Polish # 1. Zmodyfikuj funkcję `get_user` # 2. Funkcja powinna zwracać krotkę: 'Alice', 'Apricot' # 3. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> get_user() # ('Alice', 'Apricot') # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert get_user is not Ellipsis, \ 'Variable `get_user` has an invalid value; assign result of your program to it.' >>> assert isfunction(get_user), \ 'Object `get_user` must be a function' >>> get_user() ('Alice', 'Apricot') """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types from typing import Callable get_user: Callable[[], tuple[str,str]] # %% Data # %% Result def get_user(): ...
# %% About # - Name: Function Return Dict # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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 # %% English # 1. Modify function `mylocals()` # 2. Function should return a dict, # example: {'firstname': 'Alice', 'lastname': 'Apricot'} # 3. Use variables `firstname` and `lastname` # 4. Do not use built-in function `locals()` # 5. Run doctests - all must succeed # %% Polish # 1. Zmodyfikuj funkcję `mylocals` # 2. Funkcja powinna zwracać dict, # przykład: {'firstname': 'Alice', 'lastname': 'Apricot'} # 3. Użyj zmiennych `firstname` i `lastname` # 4. Nie używaj wbudowanej funkcji `locals()` # 5. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> mylocals() # {'firstname': 'Alice', 'lastname': 'Apricot'} # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert mylocals is not Ellipsis, \ 'Variable `mylocals` has an invalid value; assign result of your program to it.' >>> assert isfunction(mylocals), \ 'Object `mylocals` must be a function' >>> mylocals() {'firstname': 'Alice', 'lastname': 'Apricot'} """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types from typing import Callable mylocals: Callable[[], dict[str,str]] # %% Data # %% Result def mylocals(): firstname = 'Alice' lastname = 'Apricot' return ...
# %% About # - Name: Function Return Capture # - Difficulty: easy # - Lines: 1 # - Minutes: 2 # %% 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 # %% 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 `add` # 2. Uruchom doctesty - wszystkie muszą się powieść # %% Expected # >>> result # 3 # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> from inspect import isfunction >>> assert isfunction(add), \ 'Object `add` must be a function' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is int, \ 'Variable `result` has an invalid type; expected: `int`.' >>> result 3 """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports # %% Types result: int # %% Data def add(): return 1 + 2 # %% Result result = ...