9.3. Function Parameters

9.3.1. Rationale

parameter

Receiving variable used within the function/block

default parameter

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

required parameter

Parameter which is necessary to call function

9.3.2. Syntax

Function definition with parameters:

def myfunction(<parameters>):
    <do something>
>>> def add(a, b):
...     print(a + b)

9.3.3. Required Parameters

  • Parameters without default values are required

>>> def add(a, b):
...     print(a + b)
>>>
>>>
>>> add()
Traceback (most recent call last):
TypeError: add() missing 2 required positional arguments: 'a' and 'b'
>>> add(1)
Traceback (most recent call last):
TypeError: add() missing 1 required positional argument: 'b'
>>> add(1, 2)
3
>>> add(1, 2, 3)
Traceback (most recent call last):
TypeError: add() takes 2 positional arguments but 3 were given

9.3.4. 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 add(a=10, b=20):
...     print(a + b)
>>>
>>>
>>> add()
30
>>> add(1)
21
>>> add(1, 2)
3
>>> add(1, 2, 3)
Traceback (most recent call last):
TypeError: add() takes from 0 to 2 positional arguments but 3 were given

9.3.5. 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 add(a, b=20):
...     print(a + b)
>>>
>>>
>>> add()
Traceback (most recent call last):
TypeError: add() missing 1 required positional argument: 'a'
>>> add(1)
21
>>> add(1, 2)
3
>>> add(1, 2, 3)
Traceback (most recent call last):
TypeError: add() takes from 1 to 2 positional arguments but 3 were given
>>> def add(a=1, b):
...     print(a + b)
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument
>>> def add(a, b=1, c):
...     print(a + b + c)
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument

9.3.6. Examples

Example 1:

>>> def add(a, b):
...     print(a + b)
>>>
>>>
>>> add(1, 2)
3
>>> add(1.5, 2.5)
4.0
>>> add('a', 'b')
ab

Example 2:

>>> def echo(text):
...     print(text)
>>>
>>>
>>> echo('hello')
hello

Example 3:

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

Example 4. Definition of pandas.read_csv() function. Source: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html:

>>> 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):
...
...     print('Reading CSV...')

9.3.7. Assignments

Code 9.3. Solution
"""
* Assignment: Function Parameters Sequence
* Complexity: easy
* Lines of code: 2 lines
* Time: 3 min

English:
    1. Define function `total`
    2. Function parameter is `data` sequence of integers
    3. Function returns sum of all values in sequence
    4. Compare result with "Tests" section (see below)

Polish:
    1. Zdefiniuj funkcję `total`
    2. Parametrem do funkcji jest `data` sekwencja liczb
    3. Funkcja zwraca sumę wszystkich wartości z sekwencji
    4. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> from inspect import isfunction
    >>> isfunction(total)
    True
    >>> type(total([0, 1])) is int
    True
    >>> type(total([0.0, 1.1])) is float
    True
    >>> total([1,2,3])
    6
    >>> total([1,2,3,4,5,6])
    21
    >>> total(range(0,101))
    5050
"""


Code 9.4. Solution
"""
* Assignment: Function Parameters Echo
* Complexity: easy
* Lines of code: 2 lines
* Time: 3 min

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. Compare result with "Tests" section (see below)

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. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> from inspect import isfunction
    >>> isfunction(echo)
    True
    >>> type(echo(0,0)) is tuple
    True
    >>> echo(1, 2)
    (1, 2)
    >>> echo(3, 4)
    (3, 4)
"""


Code 9.5. Solution
"""
* Assignment: Function Parameters Default
* Complexity: easy
* Lines of code: 4 lines
* Time: 3 min

English:
    1. Define function `default` 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`
    6. Compare result with "Tests" section (see below)

Polish:
    1. Zdefiniuj funkcję `default` 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`
    6. Porównaj wyniki z sekcją "Tests" (patrz poniżej)

Tests:
    >>> from inspect import isfunction
    >>> isfunction(default)
    True
    >>> type(default(0,0)) is dict
    True
    >>> default(1)
    {'a': 1, 'b': 1}
    >>> default(2, 3)
    {'a': 2, 'b': 3}
"""