11.3. Function Parameters

  • Parameter - Receiving variable used within the 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

11.3.1. Syntax

Function definition with parameters:

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

You can also write this way, but this is not to be advised.

>>> def add(a, b): ...

11.3.2. Required Parameters

  • Parameters without default values are required

>>> def add(a, b):
...     return 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

11.3.3. 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):
...     return 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

11.3.4. 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):
...     return 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

11.3.5. Errors

>>> def add(a=1, b):
...     return a + b
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument
>>> def add(a, b=1, c):
...     return a + b + c
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument
>>> def add(a, b=1, c, d, e, f=8, g=9):
...     return a + b
Traceback (most recent call last):
SyntaxError: non-default argument follows default argument
>>> def add(a, c, d, e, b=1, f=8, g=9):
...     return a + b

11.3.6. Signature

>>> from inspect import signature
>>>
>>>
>>> def add(a, b=2):
...     return a + b
>>>
>>>
>>> signature(add)
<Signature (a, b=2)>

11.3.7. Use Case - 0x01

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

11.3.8. Use Case - 0x03

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

11.3.9. Use Case - 0x02

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

11.3.10. Use Case - 0x03

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): ...

11.3.11. Assignments

Code 11.8. Solution
"""
* Assignment: Function Parameters Square
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

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

Polish:
    1. Zdefiniuj funkcję `square`:
       a. przyjmuje `x: int`
       b. zwraca kwadrat `x`
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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
"""

# Returns square of `x`
# type: Callable[[int], int]
...


Code 11.9. Solution
"""
* Assignment: Function Parameters IsEven
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

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

Polish:
    1. Zdefiniuj funkcję `is_even`:
       a. przyjmuje `x: int`
       b. zwraca True/False czy `x` jest parzysty
    2. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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
"""

# Returns True/False if `x` is even
# type: Callable[[int], bool]
...


Code 11.10. Solution
"""
* Assignment: Function Parameters Sum
* Type: class assignment
* Complexity: easy
* Lines of code: 2 lines
* Time: 2 min

English:
    1. Define function `total`:
       a. takes `data: tuple|list|set` of objects `int | float`
       b. returns sum of all values in a sequence
    2. Run doctests - all must succeed

Polish:
    1. Zdefiniuj funkcję `total`:
       a. przyjmuje `data: tuple|list|set` obiektów `int | float`
       b. zwraca sumę wszystkich wartości z sekwencji
    2. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `sum()`

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> 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
    >>> total(range(0,101))
    5050
"""

# Returns sum of all values in a sequence
# type: Callable[[tuple|list|set], int]
...


Code 11.11. Solution
"""
* Assignment: Function Parameters Echo
* Type: class assignment
* 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. 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
    >>> 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)
"""


Code 11.12. Solution
"""
* Assignment: Function Parameters Default
* Type: class assignment
* 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`, i.e. {'a': 1, 'b': 1}
    6. Run doctests - all must succeed

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`, np. {'a': 1, 'b': 1}
    6. Uruchom doctesty - wszystkie muszą się powieść

Tests:
    >>> import sys; sys.tracebacklimit = 0
    >>> from inspect import isfunction

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

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


Code 11.13. Solution
"""
* Assignment: Function Parameters BloodPressure
* Type: class assignment
* Complexity: medium
* Lines of code: 10 lines
* Time: 13 min

English:
    1. Table contains Blood Pressure classification according to American Heart Association [1]
    2. User inputs blood pressure in `XXX/YY` or `XXX/YYY` format
    3. User will not try to input invalid data
    4. Data format:
        a. `XXX: int` systolic pressure
        b. `YY: int` or `YYY: int` diastolic pressure
    5. Print status of given blood pressure
    6. If systolic and diastolic values are in different categories, assume worst case
    7. Run doctests - all must succeed

Polish:
    1. Tabela zawiera klasyfikację ciśnienia krwi wg American Heart Association [1]
    2. Użytkownik wprowadza ciśnienie krwi w formacie `XXX/YY` lub `XXX/YYY`
    3. Użytkownik nie będzie próbował wprowadzać danych niepoprawnych
    4. Format danych:
        a. `XXX: int` to wartość ciśnienia skurczowego (ang. systolic)
        b. `YY: int` lub `YYY: int` to wartość ciśnienia rozkurczowego (ang. diastolic)
    5. Wypisz status wprowadzonego ciśnienia krwi
    6. Gdy wartości ciśnienia skurczowego i rozkurczowego należą do różnych kategorii, przyjmij gorszy przypadek
    7. Uruchom doctesty - wszystkie muszą się powieść

Hints:
    * `and`
    * `or`

References:
    [1] Whelton, Paul K. and et al.
        2017 ACC/AHA/AAPA/ABC/ACPM/AGS/APhA/ASH/ASPC/NMA/PCNA Guideline for the
        Prevention, Detection, Evaluation, and Management of High Blood Pressure
        in Adults: Executive Summary: A Report of the American College of
        Cardiology/American Heart Association Task Force on Clinical Practice Guidelines.
        Journal of Hypertension. vol 71. pages 1269–1324. 2018. doi: 10.1161/HYP.0000000000000066

Tests:
    TODO: Better Tests

    >>> import sys; sys.tracebacklimit = 0
    >>> result = blood_pressure(0,0)

    >>> assert result is not Ellipsis, \
    'Assign your result to variable `result`'

    >>> assert type(result) is str, \
    'Variable `result` has invalid type, should be str'

    >>> result in (STATUS_NORMAL, STATUS_ELEVATED, STATUS_HYPERTENSION_STAGE_1,
    ...            STATUS_HYPERTENSION_STAGE_2, STATUS_HYPERTENSIVE_CRISIS)
    True

    >>> blood_pressure(115, 75)
    'Normal'
    >>> blood_pressure(125, 75)
    'Elevated'
    >>> blood_pressure(135, 85)
    'Hypertension stage 1'
    >>> blood_pressure(145, 95)
    'Hypertension stage 2'
    >>> blood_pressure(195, 135)
    'Hypertensive Crisis'

    >>> blood_pressure(119, 0)
    'Normal'
    >>> blood_pressure(120, 0)
    'Elevated'
    >>> blood_pressure(0, 79)
    'Normal'
    >>> blood_pressure(0, 80)
    'Hypertension stage 1'
    >>> blood_pressure(120, 80)
    'Hypertension stage 1'

    >>> blood_pressure(129, 0)
    'Elevated'
    >>> blood_pressure(130, 0)
    'Hypertension stage 1'
    >>> blood_pressure(0, 79)
    'Normal'
    >>> blood_pressure(0, 80)
    'Hypertension stage 1'
    >>> blood_pressure(130, 80)
    'Hypertension stage 1'

    >>> blood_pressure(139, 0)
    'Hypertension stage 1'
    >>> blood_pressure(140, 0)
    'Hypertension stage 2'
    >>> blood_pressure(0, 89)
    'Hypertension stage 1'
    >>> blood_pressure(0, 90)
    'Hypertension stage 2'
    >>> blood_pressure(140, 90)
    'Hypertension stage 2'

    >>> blood_pressure(180, 0)
    'Hypertension stage 2'
    >>> blood_pressure(181, 0)
    'Hypertensive Crisis'
    >>> blood_pressure(0, 120)
    'Hypertension stage 2'
    >>> blood_pressure(0, 121)
    'Hypertensive Crisis'
    >>> blood_pressure(181, 121)
    'Hypertensive Crisis'
"""

STATUS_NORMAL = 'Normal'
STATUS_ELEVATED = 'Elevated'
STATUS_HYPERTENSION_STAGE_1 = 'Hypertension stage 1'
STATUS_HYPERTENSION_STAGE_2 = 'Hypertension stage 2'
STATUS_HYPERTENSIVE_CRISIS = 'Hypertensive Crisis'

# | Blood Pressure Category | Systolic [mm Hg] | Operator | Diastolic [mm Hg] |
# |-------------------------|------------------|----------|-------------------|
# | Normal                  | Less than 120    | and      | Less than 80      |
# | Elevated                | 120-129          | and      | Less than 80      |
# | Hypertension stage 1    | 130-139          | or       | 80-89             |
# | Hypertension stage 2    | 140 or higher    | or       | 90 or higher      |
# | Hypertensive Crisis     | Higher than 180  | and/or   | Higher than 120   |

# One of the STATUS_*
# type: Callable[[int,int], str]
def blood_pressure(systolic, diastolic):
    return ...