Types of Arguments in Python Functions
Arguments in Python functions are of three types:
- Positional Arguments
- Keyword Arguments
- Variable Length Arguments
Positional Arguments
>>> def calculateArea(length, breadth): print("Length:", length) print("Breadth:", breadth) print("Area:", length * breadth) >>> calculateArea(5, 6) Length: 5 Breadth: 6 Area: 30
The reason why these are called positional arguments, is that the order in which you specify is the order in which they get assigned to the parameters. That is, to say, that while calling the calculateArea() function, whatever you specify first gets assigned to the parameter length and whatever you specify second gets assigned to the parameter breadth. This is not the case with keyword arguments, which we will notice in due time.
Positional arguments are also known as Required arguments. If you declare a function with, say 4 parameters, but call it with less than 4 arguments, then Python will throw a TypeError. Again, this is in contrast to keyword arguments (with a default value).
>>> calculateArea(5) Traceback (most recent call last): # traceback info calculateArea(5) TypeError: calculateArea() missing 1 required positional argument: 'breadth'
Keyword Arguments
>>> def calculateArea(length, breadth): print("Length:", length) print("Breadth:", breadth) print("Area:", length * breadth) >>> calculateArea(breadth = 5, length = 6) Length: 6 Breadth: 5 Area: 30
If you know the parameter names, you can ask Python to assign values to parameters by their names. You can specify the order in any which way you want since you have explicitly mentioned which argument will be assigned to which parameter.
Default Arguments: Giving keyword arguments a default value
>>> def calculateArea(length = 5, breadth = 6): print("Length:", length) print("Breadth:", breadth) print("Area:", length * breadth) >>> calculateArea() Length: 5 Breadth: 6 Area: 30 >>> >>> calculateArea(10, 3) Length: 10 Breadth: 3 Area: 30 >>> >>> calculateArea(12) # assumes the provided value for first parameter, keeping the default value for the second. Length: 12 Breadth: 6 Area: 72 >>> >>> calculateArea(breadth = 10) Length: 5 Breadth: 10 Area: 50
Keyword arguments support default values in the event that the user doesn't provide a value for that parameter in the function call.
Variable Length Arguments
Sometimes, the situation demands you to handle more parameters than you define the function with. In such a case, you can declare a tuple as a parameter, which will hold the surplus arguments. Example below will make it clear.
>>> def collectParameters(length, breadth, *other_dimensions): print("Length:",length) print("Breadth:", breadth) print("Other Dimensions:", other_dimensions) print(type(other_dimensions)) >>> collectParameters(10, 20, 30, 40, 50, 60) Length: 10 Breadth: 20 Other Dimensions: (30, 40, 50, 60) <class 'tuple'> >>> collectParameters(10, 20) Length: 10 Breadth: 20 Other Dimensions: () <class 'tuple'>