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¶
"""
* Assignment: Function Parameters Square
* Required: yes
* 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]
...
"""
* Assignment: Function Parameters IsEven
* Required: yes
* 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]
...
"""
* Assignment: Function Parameters Sum
* Required: yes
* 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]
...