Social Media

2/05/2019

Types of arguments in a function

There can be different types of arguments which a function can have. These are as follows:
  • Default arguments
  • Positional arguments
  • Keyword arguments
  • Variable length arguments
  • Variable length keyword arguments
Default arguments: The usage of default argument is shown below in the simple python script.

def addition(a,b,c=0):
    return a+b+c

x=addition(2,3)
y=addition(2,3,4)
print(x,y) # 5 9

Here addition function can accept maximum three arguments and minimum two arguments. If we pass only two arguments then third argument will automatically initialized to 0 and we get the sum of two arguments in return.
If we pass three arguments then third argument hold that value which is passed by us and in return we get the sum of three numbers.

Positional and keyword arguments:
def f1(x,y):
    print("x=",x,"y=",y)

f1(1,2) # Positional arguments
f1(x=1,y=2) # Keyword arguments
f1(y=1,x=2) # Keyword arguments

f1(x=1,y) # error comes
f1(3,x=3) # error comes
In keyword arguments order is not really important. You can pass the keyword argument in any order you want, but in case of positional arguments order matters.

Note* Positional arguments can never come after keyword arguments, if we do so error will come.

Be First to Post Comment !
Post a Comment