Arguments and Parameters
tags: #python/documentation/python_functions
Understanding Parameters and Arguments
Parameters
Parameters are variables defined in the function. The parameters act a placeholders that get replaced with the input values that the function expects when it is called.
Arguments
An argument is the actual value that is passed through the function when it is called. This value is assigned to the corresponding parameter defined inside the function.
When invoking a function, a value should be provided to each associated parameters.
How can we arguments be specified?
There are 2 ways arguments can be passed. However, by default, parameters have a positional behaviour (exception: named arguments, which can be given in any order).
Positional Passing
Positional arguments are values that are passed into a function based on the order in which the parameters were listed during the function definition.
In this case, the order is especially important as values passed into these functions are assigned to corresponding parameters based on their position.
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")
greet("Alice", 25)
Keyword-Based Passing
Keyword arguments can be likened to dictionaries in that they map a value to a keyword (parameter) defined in the function:
kwarg = {parameter: argument, ...}
myFunction(**kwargs)
This is a way to pass any number of named arguments to a function, which Python collects into a dictionary inside the function.
In this case, arguments are passed by explicitly mentioning the parameter names along with their values in the function call. This allows you to specify which value corresponds to which parameter regardless of their order.
def greet(name, age, city):
print(f"Hello {name}, age {age}, from {city}")
data = {"name": "Bob", "age": 25, "city": "Vancouver"}
greet(**data) # same as greet(name="Bob", age=25, city="Vancouver")
This is most useful when there are many optional parameters and you want to provide a value for only a select few.
- You can pass keyword args or a dict that you unpack with
**kwarg.- In this case, you are passing a dictionary that Python unpacks into keyword arguments.