14.3. Function Parameters

  • Parameter - What you specify while defining a function

  • Required parameter - necessary to call that function

  • Required parameter - specified at leftmost side

  • Default parameter - optional to call that function

  • Default parameter - Has default value

  • Default parameter - Could be overridden

  • Default parameter - Specified at rightmost side

parameter

Receiving variable used within the function/block

required parameter

Parameter which is necessary to call function

default parameter

Parameter which is optional and has default value (if not specified at call time)

signature

Function name and its parameters

Syntax:

def myfunction(<parameters>):
    return ...

Example:

>>> def login(username, password):
...     return ...

14.3.1. Required Parameters

  • Parameters without default values are required

>>> def login(username, password):
...     return ...

14.3.2. Default Parameters

  • Default parameters has default value

  • Function will use default value if not overwritten by user

  • Parameters with default values can be omitted while executing

>>> def login(username=None, password=None):
...     return ...

14.3.3. Required and Default Parameters

  • Required parameters must be at the left side

  • Default parameters must be at the right side

  • There cannot be required parameter after optional

>>> def login(username, password=None):
...     return ...

14.3.4. Errors

>>> def login(username=None, password):
...     return ...
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default

14.3.5. Help

  • Signature - Name and parameters of a function

>>> def login(username, password=None):
...     return ...
>>>
>>> help(login)
Help on function login in module __main__:

login(username, password=None)

14.3.6. Use Case - 1

>>> def echo(text):
...     return text

14.3.7. Use Case - 2

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

14.3.8. Use Case - 3

>>> def connect(username, password, host='127.0.0.1', port=22,
...             ssl=True, keep_alive=1, persistent=False): ...

14.3.9. Use Case - 4

Definition of pandas.read_csv() function:

>>> def read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer',
...              names=None, index_col=None, usecols=None, squeeze=False,
...              prefix=None, mangle_dupe_cols=True, dtype=None, engine=None,
...              converters=None, true_values=None, false_values=None,
...              skipinitialspace=False, skiprows=None, nrows=None,
...              na_values=None, keep_default_na=True, na_filter=True,
...              verbose=False, skip_blank_lines=True, parse_dates=False,
...              infer_datetime_format=False, keep_date_col=False,
...              date_parser=None, dayfirst=False, iterator=False,
...              chunksize=None, compression='infer', thousands=None,
...              decimal=b'.', lineterminator=None, quotechar='"',
...              quoting=0, escapechar=None, comment=None, encoding=None,
...              dialect=None, tupleize_cols=None, error_bad_lines=True,
...              warn_bad_lines=True, skipfooter=0, doublequote=True,
...              delim_whitespace=False, low_memory=True, memory_map=False,
...              float_precision=None): ...

14.3.10. 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 Parameters Square
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define function `square`:
#    - takes `x: int`
#    - returns square of `x`
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `square`:
#    - przyjmuje `x: int`
#    - zwraca kwadrat `x`
# 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 square is not Ellipsis, \
'Write solution inside `square` function'
>>> assert isfunction(square), \
'Object `square` must be a function'

>>> square(2)
4
>>> square(8)
64
>>> square(32)
1024
"""

# Define function `square`:
# - takes `x: int`
# - returns square of `x`
# type: Callable[[int], int]
...


# %% 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 Parameters IsEven
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define function `is_even`:
#    - takes `x: int`
#    - returns True/False if `x` is even
# 2. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `is_even`:
#    - przyjmuje `x: int`
#    - zwraca True/False czy `x` jest parzysty
# 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 is_even is not Ellipsis, \
'Write solution inside `is_even` function'
>>> assert isfunction(is_even), \
'Object `is_even` must be a function'

>>> is_even(2)
True
>>> is_even(3)
False
>>> is_even(4)
True
>>> is_even(5)
False
>>> is_even(6)
True
>>> is_even(7)
False
"""

# Define function `is_even`:
# - takes `x: int`
# - returns True/False if `x` is even
# type: Callable[[int], bool]
...


# %% 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 Parameters Sum
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define function `total`:
#    - takes `data: list[int|float]`
#    - returns sum of all values in a list
# 2. Do not use built-in `sum()` function
# 3. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `total`:
#    - przyjmuje `data: list[int|float]`
#    - zwraca sumę wszystkich wartości z listy
# 2. Nie używaj wbudowanej funkcji `sum`
# 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 total is not Ellipsis, \
'Write solution inside `total` function'
>>> assert isfunction(total), \
'Object `total` must be a function'

>>> total([1,2,3])
6
>>> total([1,2,3,4,5,6])
21
"""

# Define function `total`:
# - takes `data: list[int|float]`
# - returns sum of all values in a list
# Do not use built-in `sum()` function
# type: Callable[[tuple|list|set], int]
...


# %% 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 Parameters Echo
# - Difficulty: easy
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Define function `echo` with two parameters
# 2. Parameter `a` is required
# 3. Parameter `b` is required
# 4. Return `a` and `b` as a `tuple`
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `echo` z dwoma parametrami
# 2. Parametr `a` jest wymagany
# 3. Parametr `b` jest wymagany
# 4. zwróć `a` i `b` jako `tuple`
# 5. 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 echo is not Ellipsis, \
'Write solution inside `echo` function'
>>> assert isfunction(echo), \
'Object `echo` must be a function'

>>> echo(1, 2)
(1, 2)
>>> echo(3, 4)
(3, 4)
"""

# Define function `echo` with two parameters
# Parameter `a` is required
# Parameter `b` is required
# Return `a` and `b` as a `tuple`
# type: Callable[[int, int], tuple[int, int]]


# %% 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 Parameters Default
# - Difficulty: easy
# - Lines: 4
# - Minutes: 2

# %% English
# 1. Define function `result` with two parameters
# 2. Parameter `a` is required
# 3. Parameter `b` is optional and has default value `None`
# 4. If only one argument was passed, consider second equal to the first one
# 5. Return `a` and `b` as a `dict`, i.e. {'a': 1, 'b': 1}
# 6. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj funkcję `result` z dwoma parametrami
# 2. Parametr `a` jest wymagany
# 3. Parametr `b` jest opcjonalny i ma domyślną wartość `None`
# 4. Jeżeli tylko jeden argument był podany, przyjmij drugi równy pierwszemu
# 5. Zwróć `a` i `b` jako `dict`, np. {'a': 1, 'b': 1}
# 6. 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 result is not Ellipsis, \
'Write solution inside `result` function'
>>> assert isfunction(result), \
'Object `result` must be a function'

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

# Define function `result` with two parameters
# Parameter `a` is required
# Parameter `b` is optional and has default value `None`
# If only one argument was passed, consider second equal to the first one
# Return `a` and `b` as a `dict`, i.e. {'a': 1, 'b': 1}
...