Types of Arguments
There are 4 types how we can pass arguments to functions in python
1) Default arguments
2) Required arguments
3) Keyword arguments
4) Variable number of arguments
Default arguments: Default values indicate that the function argument will take that value if no argument value is passed during function call. The default value is assigned by using assignment (=) operator.
EX:
### Function definition
def display(name,age=23):
print(name,age)### Function call
display(name=’jack’)
display(name=’tom’,age=32)
display(age=16,name=’jerry’)
o/p
jack 23 tom 32 jerry 16
Required arguments: Required arguments are the mandatory arguments of a function. These argument values must be passed in correct number and order during function call.
Ex:
### Function definition
def display(city,timezone):
print(city,timezone)### Function call
display(‘hyderabad’,’GMT’)
display(timezone=’GMT’,city=’hyd’)
display(‘hyderabad’)
o/p:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-18-bab62319b1b8> in <module> 6 display('hydetabad','GMT') 7 display(timezone='GMT',city='hyd') ----> 8 display('hyderabad') TypeError: display() missing 1 required positional argument: 'timezone'
Keyword arguments: The keywords are mentioned during the function call along with their corresponding values. These keywords are mapped with the function arguments so the function can easily identify the corresponding values even if the order is not maintained during the function call.
Ex:
### Function definition
def display(country,capital):
print(country,capital)### Function call
display(country=’india’,capital=’delhi’)
display(capital=’washington’,country=’usa’)
display(country=’china’)
o/p
Variable number of arguments: This is very useful when we do not know the exact number of arguments that will be passed to a function.
Ex:
### Function definition
def display(*languages):
for i in languages:
print(i)### Function call
display(‘c’,’java’,’python’,’dotnet’,’cobal’)
o/p:
