In Python , a function can have 4 types of arguments:
These are the arguments passed to a function in correct positional order.
Here the number of arguments in the call must exactly match with number of parameters in the function definition
If the number of arguments in call do not match with the number of parameters in function then we get TypeError.
Example
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery("Bread",20)
grocery(150,"Butter")
Output:
Item is Bread It's price is 20
Item is 150 It's price is Butter
The problem with positional arguments is that they always bind to the position of parameters.
So 1st argument will be copied to 1st parameter , 2nd argument will be copied to 2nd parameter and so on.
Due to this in the previous example the value 150 was copied to name and “Butter” was copied to price
To solve this problem , Python provides us the concept of keyword arguments
Keyword arguments are arguments that identify parameters with their names
With keyword arguments in Python, we can change the order of passing the arguments without any consequences
Syntax:
function_name(paramname1=value,paramname2=value)
Example:
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery(name="Bread",price=20)
grocery(price=150,name="Butter")
Output:
Item is Bread It's price is 20
Item is Butter It's price is 150
Point to remember!!
For some functions, we may want to make some parameters optional and use default values in case the user does not want to provide values for them.
This is done with the help of default argument values.
We can specify default argument values for parameters by appending to the parameter name in the function definition the assignment operator (=) followed by the default value.
Syntax:
def function_name(paramname1=value,paramname2=value):
# function body
Example:
def greet(name,msg="Good Morning"):
print("Hello",name,msg)
greet("Chitranshi")
greet("Aditi","How are you?")
Output:
Hello Chitranshi Good Morning
Hello Aditi How are you?
Point to remember! In this technique , we define the function in such a way that it can accept any number of arguments from 0 to infinite Syntax of Variable Length Argument:
def <function_name>(* >arg_name<):
Function body
As we can observe , to create a function with variable length arguments we simply prefix the argument name with an asterisk.
def addnos(*a):
The function addnos() can now be called with as many number of arguments as we want and all the arguments will be stored inside the argument a which will be internally treated as tuple
def addnos(*a):
sum =0
for x in a:
sum=sum+x
return sum
print(addnos(10,20))
print(addnos(10,20,30))
Output:
30
60
Point yo remember!!
def addnos(*a,*b):
If we have any other argument along with variable length argument , then it should be set before the variable length argument