15.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>):
pass
Example:
>>> def login(username, password):
... pass
15.3.1. Required Parameters
Parameters without default values are required
>>> def login(username, password):
... pass
15.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):
... pass
15.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):
... pass
15.3.4. Errors
>>> def login(username=None, password):
... pass
Traceback (most recent call last):
SyntaxError: parameter without a default follows parameter with a default
15.3.5. Help
Signature - Name and parameters of a function
>>> def login(username, password=None):
... pass
>>>
>>> help(login)
Help on function login in module __main__:
login(username, password=None)
15.3.6. Recap
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
>>> def login(username, password=None):
... pass
Function is called
login.It has two parameters -
usernameandpassword.usernameis a required parameter.passwordis a default parameter with default value ofNone.
15.3.7. Use Case - 1
>>> def echo(text):
... return text
15.3.8. Use Case - 2
>>> def age_category(age):
... if age < 18:
... return 'junior'
... else:
... return 'senior'
>>> age_category(10)
'junior'
>>> age_category(41)
'senior'
15.3.9. Use Case - 3
>>> def connect(username, password, host='127.0.0.1', port=22,
... ssl=True, keep_alive=1, persistent=False): ...
15.3.10. 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): ...
15.3.11. Assignments
# %% About
# - Name: Function Parameters Square
# - 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. Define function `square`:
# - takes `x`
# - returns `x` squared
# 2. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `square`:
# - przyjmuje `x`
# - zwraca `x` do kwadratu
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> square(8)
# 64
# %% 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 square is not Ellipsis, \
'Variable `square` has an invalid value; assign result of your program to it.'
>>> assert isfunction(square), \
'Object `square` must be a function'
>>> square(2)
4
>>> square(8)
64
>>> square(32)
1024
"""
# %% 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
square: Callable[[int], int]
# %% Data
# %% Result
# %% About
# - Name: Function Parameters IsEven
# - 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. Define function `is_even`:
# - takes `x`
# - returns True/False if `x` is even
# 2. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `is_even`:
# - przyjmuje `x`
# - zwraca True/False czy `x` jest parzysty
# 2. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> is_even(1)
# False
#
# >>> is_even(2)
# True
# %% 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 is_even is not Ellipsis, \
'Variable `is_even` has an invalid value; assign result of your program to it.'
>>> 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
"""
# %% 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
is_even: Callable[[int], bool]
# %% Data
# %% Result
# %% About
# - Name: Function Parameters Sum
# - 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. Define function `mysum`:
# - takes `data`
# - 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ę `mysum`:
# - przyjmuje `data`
# - zwraca sumę wszystkich wartości z listy
# 2. Nie używaj wbudowanej funkcji `sum`
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> mysum([1, 2, 3])
# 6
# %% 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 mysum is not Ellipsis, \
'Variable `mysum` has an invalid value; assign result of your program to it.'
>>> assert isfunction(mysum), \
'Object `mysum` must be a function'
>>> mysum([1, 2, 3])
6
>>> mysum([1, 2, 3, 4, 5, 6])
21
"""
# %% 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
mysum: Callable[[tuple|list|set], int|float]
# %% Data
# %% Result
# %% About
# - Name: Function Parameters mylocals
# - 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. Define function `mylocals` with two parameters
# 2. Parameter `firstname` is required
# 3. Parameter `lastname` is required
# 4. Return `firstname` and `lastname` as a `dict`,
# example: {'firstname': 'Alice', 'lastname': 'Apricot'}
# 5. Do not use built-in function `locals()`
# 6. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `mylocals` z dwoma parametrami
# 2. Parametr `firstname` jest wymagany
# 3. Parametr `lastname` jest wymagany
# 4. Zwróć `firstname` i `lastname` jako `dict`,
# przykład: {'firstname': 'Alice', 'lastname': 'Apricot'}
# 5. Nie używaj wbudowanej funkcji `locals()`
# 6. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> mylocals('Alice', 'Apricot')
# {'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('Alice', 'Apricot')
{'firstname': 'Alice', 'lastname': 'Apricot'}
>>> mylocals('Bob', 'Blackthorn')
{'firstname': 'Bob', 'lastname': 'Blackthorn'}
"""
# %% 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[[int, int], dict[str, int]]
# %% Data
# %% Result
# %% About
# - Name: Function Parameters Default
# - Difficulty: easy
# - Lines: 4
# - 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 function `mypow` with two parameters
# 2. Parameter `base` is required
# 3. Parameter `exp` is optional and has default value `2`
# 4. Return `base` raised to the power of `exp`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `mypow` z dwoma parametrami
# 2. Parametr `base` jest wymagany
# 3. Parametr `exp` jest opcjonalny i ma domyślną wartością `2`
# 4. Zwróć `base` podniesione do potęgi `exp`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Expected
# >>> mypow(2)
# 4
#
# >>> mypow(base=2)
# 4
#
# >>> mypow(2, 10)
# 1024
#
# >>> mypow(base=2, exp=10)
# 1024
# %% 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 mypow is not Ellipsis, \
'Variable `mypow` has an invalid value; assign result of your program to it.'
>>> assert isfunction(mypow), \
'Object `mypow` must be a function'
>>> mypow(2)
4
>>> mypow(base=2)
4
>>> mypow(2, 10)
1024
>>> mypow(base=2, exp=10)
1024
"""
# %% 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
mypow: Callable[[int, int|None], int]
# %% Data
# %% Result