Parameters and Arguments

Python functions have the ability to take input to regulate their operation. A function call provides this information.
Although the phrases arguments and parameters are sometimes used interchangeably, they have different meanings.
- The named entities specified in the function header (the first line of the function declaration) are called parameters. They serve as stand-ins for the data that the function requires. Parameterised variables are specific to the function.
- The actual values or data that are passed into the function when it is called are called arguments. Within the function, the values of the arguments are copied to the appropriate parameters. A piece of data sent from a function call to a function is called an argument.
Formal Arguments/Parameters
All parameters given during invocation that directly correspond to those in the function declaration’s argument list make up the formal arguments of a function. This covers parameters with default values, keyword arguments matched by name, and mandatory arguments provided positionally. When the function starts running, a name is generated for the value in the local namespace.
Here is a simple example of a function definition with formal parameters and a call with arguments:
Example:
# here a and b are parameters
def add(a, b)
return a + b
# 12 and 13 are arguments
add(12, 13)
The formal parameters in this case are a and b. The arguments for add(12,13) are 12 and 13, and parameter an is allocated the value 12, while parameter b is assigned the value 13.
You can pass information to functions in several ways
Positional Arguments
Python matches each argument in the function call to a parameter in the function declaration according to their order when positional arguments are used. Arguments must be supplied in the same sequence as the parameters.
Example:
def describe pet(animal type, pet name)
Display information about a pet.
print(f"nI have a {animal type}.")
print(f My {animal type}'s name is {pet name title()}.")
describe pet('hamster', 'harry')
‘Harry’ is assigned to pet name and ‘hamster’ to animal type in this call due to their respective positions. Remembering what each position means is a drawback of positional arguments.
Keyword Arguments (Named Arguments)
You can specify arguments using the names of their corresponding parameters in the function call to prevent confusion or in situations when the order of these arguments isn’t crucial. “parameter
name=value” is the syntax. It makes no difference what order the keyword parameters are in the call.
Example:
def menu(wine, entree, dessert)
return {'wine': wine, 'entree': entree, 'dessert': dessert}
# Calling with keyword arguments, order doesn't matter
print(menu(dessert='cake', wine='chardonnay', entree='chicken'))
Output:
{'wine': 'chardonnay', 'entree': 'chicken', 'dessert': 'cake'}
By labelling the data, keyword arguments help calls become more self-documenting.
Mixing Positional and Keyword Arguments:
Combining Positional and Keyword Arguments: When calling a function, you can combine positional and keyword arguments. All positional arguments must be used before any keyword arguments when mixing.
Example:
def process(a, b, c):
print('a =', a, ' b =', b, ' c =', c)
# Positional argument first, then keyword arguments
process(10000, c=30000, b=20000
Output:
a = 10000 b = 20000 c = 30000
The keyword arguments c=30000 and b=20000 are then assigned to their respective parameters after the initial argument, 10,000, is positionally given to a.
Default Parameter Values
Parameter default values can be specified by functions. As a result, these arguments are not required when calling the function. For a parameter having a default value, the default value is utilised if no argument is supplied. In the function definition, parameters with default values have to come after any parameters without default values.
Example:
# date string has a default value of
def hello(fname, lname, datestring=''):
print(f"Hello {fname} {lname}{' on ' + date string if date string else ''}")
# Call without the optional argument (default is used)
hello("Alan", "Simpson")
Output:
Hello Alan Simpson
Example:
# Call with all arguments
hello("Jane", "Doe", "Monday")
Output:
# Output: Hello Jane Doe on Monday
Example:
# Default arguments can be overridden using keyword arguments
def func(a, b=5, c=10):
print(a, b, c)
func(25, c=24) # 'a' gets 25 (position), 'c' gets 24 (keyword), 'b' gets 5 (default)
Output:
25 5 24
Variable-Length Arguments (Arbitrary Arguments)
The precise number of arguments a function will receive is sometimes unknown. Python uses a unique syntax in the function specification to allow functions to take a variable number of parameters.
A configurable number of non-keyworded (positional) arguments can be accepted using the args function. An asterisk () appears before a parameter name (usually args) in the function specification. Within the function, these arguments are compiled into a tuple.
Example:
# opt nums collects any extra positional arguments into a tuple
def display nums(first num, second num, opt nums):
print(first num)
print(second num)
print(opt nums) # prints the tuple
# Call with more positional arguments than defined parameters
display nums(100, 200, 300, 400, 500)
Output:
# 100
# 200
# (300, 400, 500)
A configurable number of keyworded arguments can be accepted with kwargs. A parameter name (usually kwargs) is preceded by a double asterisk (). Within the function, these arguments are gathered into a dictionary, where the values of the arguments become the dictionary values and the names of the keywords become keys.
Example:
# theRest collects any extra keyword arguments into a dictionary
def dictVarArgs(arg1, arg2='defaultB', theRest):
print('formal arg1:', arg1)
print('formal arg2:', arg2)
for eachXtrArg in theRest.keys():
print('Xtra arg %s: %s' % (eachXtrArg, str(theRest[eachXtrArg])))
print('kwargs dictionary:', theRest)
# Call with extra keyword arguments
dictVarArgs(1220, 740.0, c='grail', d='python')
Output:
# formal arg1: 1220
# formal arg2: 740.0
# Xtra arg c: grail
# Xtra arg d: python
# **kwargs dictionary: {'c': 'grail', 'd': 'python'}
Example:
# Call using only keyword arguments, matching arg1 and arg2, plus extras
dictVarArgs(arg2='tales', c=123, d='poe', arg1='mystery')
Output:
# formal arg1: mystery
# formal arg2: tales
# Xtra arg c: 123
# Xtra arg d: poe
# kwargs dictionary:{'c': 123, 'd': 'poe'}
Combining all types: In a single function definition, you can include ordinary parameters, positional variable arguments (args), and keyword variable arguments (kwargs). The function definition must be written in the following order: ordinary parameters, args, and kwargs.
Keyword-only arguments are those that can only be supplied by a keyword in the function call. They appear after args but before kwargs (or if kwargs is not present).
Example:
# This function accepts a regular argument, variable positional args,
# and variable keyword args in the required order
def cheese shop(kind, args, kwargs):
print(f"Do you have any {kind} ?")
print(f"I'm sorry, we're all out of {kind}")
for arg in args:
print(arg)
print("-" 40)
for kw in kwargs:
print(kw, ":", kwargs[kw])
# Example call using all types
cheese shop("Limburger"
"It's very runny, sir.", "It's really very, VERY runny, sir.",
shop keeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
Output:
# Do you have any Limburger ?
# I'm sorry, we're all out of Limburger
# It's very runny, sir.
# It's really very, VERY runny, sir.
# shop keeper : Michael Palin
# client : John Cleese
# sketch : Cheese Shop Sketch