Python Function Parameters and Arguments
Parameters are variables defined in a function declaration. This act as placeholders for the values (arguments) that will be passed to the function.
Arguments are the actual values that you pass to the function when you call it. These values replace the parameters defined in the function.
Although these terms are often used interchangeably, they have distinct roles within a function. This article focuses to clarify them and help us to use Parameters and Arguments effectively.
Table of Content
Parameters
A parameter is the variable defined within the parentheses when we declare a function.
Example:
# Here a,b are the parameters
def sum(a,b):
print(a+b)
sum(1,2)
Output
3
Arguments
An argument is a value that is passed to a function when it is called. It might be a variable, value or object passed to a function or method as input.
Example:
def sum(a,b):
print(a+b)
# Here the values 1,2 are arguments
sum(1,2)
Output
3
Types of arguments in python
Python functions can contain two types of arguments:
- Positional Arguments
- Keyword Arguments
Positional Arguments
Positional Arguments are needed to be included in proper order i.e the first argument is always listed first when the function is called, second argument needs to be called second and so on.
Example:
def fun(s1,s2):
print(s1+s2)
fun("Geeks","forGeeks")
Output
GeeksforGeeks
Note: The order of arguments must match the order of parameters in the function definition.
Variable-Length Positional Arguments
To handle multiple arguments within the function, you can use *args.
def fun(*args):
# Concatenate all arguments
result = "".join(args)
print(result)
# Function calls
fun("Geeks", "forGeeks") # Two arguments
To read in detail, refer - *args and **kwargs in Python
Keyword Arguments
Keyword Arguments is an argument passed to a function or method which is preceded by a keyword and equal to sign (=). The order of keyword argument with respect to another keyword argument does not matter because the values are being explicitly assigned.
def fun(s1, s2):
print(s1 + s2)
# Here we are explicitly assigning the values
fun(s1="Geeks", s2="forGeeks")
Output
GeeksforGeeks