14.4. Function Arguments
Argument - value/variable/reference being passed to the function
Positional argument - value passed to function - order is important
Keyword argument - value passed to function resolved by name - order is not important
- argument
Value/variable/reference being passed to the function
- positional argument
Value passed to function - order is important
- keyword argument
Value passed to function resolved by name - order is not important
Syntax:
myfunction(<arguments>)
Example:
>>> myfunction(1, 2)
>>> myfunction(a=1, b=2)
>>> myfunction(1, b=2)
14.4.1. SetUp
>>> def login(username, password=None):
... print(f'{username=}\n{password=}')
14.4.2. Positional Arguments
Order of positional arguments has significance
Positional arguments are resolved by order. This mean, that the first argument will be assigned to the first parameter, and the second argument to the second parameter and so on:
>>> login('mwatney', 'Ares3')
username='mwatney'
password='Ares3'
The order of positional parameters is important:
>>> login('Ares3', 'mwatney')
username='Ares3'
password='mwatney'
14.4.3. Keyword Arguments
Order of keyword arguments has no significance
Keyword arguments are resolved by name instead of the position. This mean, that the argument with particular name will be assigned to the corresponding parameter with the same name in function signature.
>>> login(username='mwatney', password='Ares3')
username='mwatney'
password='Ares3'
The order of keyword parameters is not important, because values are assigned by name, not a position:
>>> login(password='Ares3', username='mwatney')
username='mwatney'
password='Ares3'
14.4.4. Positional and Keyword Arguments
Positional arguments must be at the left side
Keyword arguments must be at the right side
All positional arguments must be on the left side, and all the required arguments must be on the right side:
>>> login('mwatney', password='Ares3')
username='mwatney'
password='Ares3'
14.4.5. Errors
Positional argument follows keyword argument
Multiple values for argument
Passing positional argument which follows keyword argument will yield a
SyntaxError
:
>>> login(username='mwatney', 'Ares3')
Traceback (most recent call last):
SyntaxError: positional argument follows keyword argument
Positional argument are resolved first. Defining keyword argument which follows
positional argument with the same name will yield a TypeError
:
>>> login('mwatney', username='Ares3')
Traceback (most recent call last):
TypeError: login() got multiple values for argument 'username'
14.4.6. Use Case - 1
>>> def say_hello(text='say what?'):
... return text
>>>
>>>
>>> say_hello('hello')
'hello'
>>>
>>> say_hello(text='hello world')
'hello world'
>>>
>>> say_hello()
'say what?'
14.4.7. Use Case - 2
>>> def connect(*args, **kwargs):
... pass
>>> connect('myusername', 'mypassword')
>>> connect('myusername', 'mypassword', 'example.com', 443, False, 1, True)
>>> connect(host='example.com', username='myusername', password='mypassword')
>>> connect(
... host='example.com',
... username='myusername',
... password='mypassword',
... port=443,
... ssl=True,
... persistent=True)
14.4.8. Use Case - 3
Calling function with positional only arguments is insane. In Python we don't do that, because we have keyword arguments.
>>> read_csv('/tmp/myfile.csv', ';', None, 'infer', None, None, None, False,
... None, True, None, None, None, None, None, False, None, None,
... None, True, True, False, True, False, False, False, None, False,
... False, None, 'infer', None, b',', None, '"', 0, None, None,
... None, None, None, True, True, 0, True, False, True, False, None)
Keyword arguments with sensible defaults are your best friends. The number of function parameters suddenly is not a problem:
>>> read_csv('myfile.csv')
>>> read_csv('myfile.csv', delimiter=';', encoding='utf-8')
>>> read_csv('myfile.csv', delimiter=';', encoding='utf-8', parse_dates=['birthdate'])
>>> read_csv('myfile.csv', delimiter=';', skiprows=3)
>>> read_csv('myfile.csv',
... delimiter=';',
... encoding='utf-8',
... skiprows=3,
... usecols=['firstname', 'lastname', 'birthdate'],
... parse_dates=['birthdate'],
... )
14.4.9. Assignments
# FIXME: to zadanie bardziej pasuje do function_parameters
# %% 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 Arguments Sequence
# - Difficulty: easy
# - Lines: 2
# - Minutes: 3
# %% English
# 1. Define function `total`:
# - parameter: list of integers (required)
# - return: sum only even numbers
# 2. Use `even()` to check if number is even
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `total`:
# - parametr: lists liczb całkowitych (wymagany)
# - zwraca: sumę tylko parzystych liczb
# 2. Użyj `even()` do sprawdzenia czy liczba jest parzysta
# 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'
>>> data = [1, 2, 3, 4]
>>> total(data)
6
>>> data = [2, -1, 0, 2]
>>> total(data)
4
>>> data = list(range(0,101))
>>> total(data)
2550
"""
def even(x):
return x % 2 == 0
# Define function `total()`:
# - parameter: sequence of integers
# - return: sum only even numbers
# Use `even()` to check if number is even
# type: Callable[[list[int]], int]
def total():
...
# FIXME: to zadanie bardziej pasuje do function_parameters
# %% 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 Arguments Divide
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3
# %% English
# 1. Define function `divide`:
# - parameter `a: int` - first number (required)
# - parameter `b: int` - second number (required)
# - return result of division of both arguments
# 2. If division cannot be made
# - print "Argument `b` cannot be zero"
# - return None
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `divide`:
# - parametr `a: int` - pierwsza liczba (wymagany)
# - parametr `b: int` - druga liczba (wymagany)
# - zwróć wynik dzielenia obu argumentów
# 2. Jeżeli dzielenie nie może być wykonane
# - wypisz "Argument `b` cannot be zero"
# - zwróć None
# 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 divide is not Ellipsis, \
'Write solution inside `divide` function'
>>> assert isfunction(divide), \
'Object `divide` must be a function'
>>> divide(4, 0)
Argument `b` cannot be zero
>>> divide(4, 2)
2.0
"""
# Define function `divide`:
# - parameter `a: int` - first number (required)
# - parameter `b: int` - second number (required)
# - return result of division of both arguments
# If division cannot be made
# - print "Argument `b` cannot be zero"
# - return None
# type: Callable[[int, int], float]
def divide(a, b):
...
# FIXME: to zadanie bardziej pasuje do function_parameters
# %% 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 Arguments Power
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3
# %% English
# 1. Define function `power`:
# - parameter `a: int` - first number (required)
# - parameter `b: int` - second number (optional)
# - returns: power of the first argument to the second
# 2. If only one argument was passed,
# consider second equal to the first one
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `power`:
# - parametr `a: int` - pierwsza liczba (wymagany)
# - parametr `b: int` - druga liczba (opcjonalny)
# - zwraca: wynik pierwszego argumentu do potęgi drugiego
# 2. Jeżeli tylko jeden argument był podany,
# przyjmij drugi równy pierwszemu
# 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 power is not Ellipsis, \
'Write solution inside `power` function'
>>> assert isfunction(power), \
'Object `power` must be a function'
>>> power(4, 3)
64
>>> power(3)
27
"""
# Define function `power`:
# - parameter `a: int` - first number (required)
# - parameter `b: int` - second number (optional)
# - returns: power of the first argument to the second
# If only one argument was passed,
# consider second equal to the first one
# type: Callable[[int, int], int]
def power():
...
# FIXME: to zadanie bardziej pasuje do function_parameters
# %% 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 Arguments Translate
# - Difficulty: easy
# - Lines: 2
# - Minutes: 5
# %% English
# 1. Define function `translate`:
# - parameter `text: str` (required)
# - return `str` with translated text
# 2. If letter is in `PL` then substitute letter,
# otherwise take original letter
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj funkcję `translate`:
# - parametr `text: str` (wymagany)
# - zwróć `str` z przetłumaczonym tekstem
# 2. Jeżeli litera jest w `PL` to podmień literę,
# w przeciwnym przypadku to weź oryginalną literę
# 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 translate is not Ellipsis, \
'Write solution inside `translate` function'
>>> assert isfunction(translate), \
'Object `translate` must be a function'
>>> translate('zażółć')
'zazolc'
>>> translate('gęślą')
'gesla'
>>> translate('jaźń')
'jazn'
>>> translate('zażółć gęślą jaźń')
'zazolc gesla jazn'
"""
PL = {
'ą': 'a',
'ć': 'c',
'ę': 'e',
'ł': 'l',
'ń': 'n',
'ó': 'o',
'ś': 's',
'ż': 'z',
'ź': 'z',
}
# Define function `translate`:
# - parameter `text: str` (required)
# - return `str` with translated text
# If letter is in `PL` then substitute letter,
# otherwise take original letter
# type: Callable[[str], str]
def translate():
...