Passing Multiple Arguments to Function in Python
Hello programmers, in this tutorial we will see how to pass multiple arguments to a function in Python.
Routine and Function
Before we start, we should understand what a routine and a function are.
Routine: A group of instructions/statements given by the user which performs specific computations.
A function is a part of a program routine. Functions can be designed for various purposes.
Parameters and Arguments
Parameters: Comma-separated identifiers which follow the function name.
Arguments: The number of items in the parameter list.
Template of a Function
The introductory template of a function with arguments in Python looks like this:
def functionName(*args, **kwargs): pass #function body
Special Symbols
In Python, we can pass multiple arguments using some special symbols. The special symbols are:
- *args – used to pass a non-keyworded variable number of arguments to a function
- **kwargs – used to pass a keyworded variable number of arguments dictionary to a function
Illustration of a function using *args in Python
def printMultipleValues(*args): count = 0 for i in args: print(f"Argument value {count+1} is: {i}") count += 1 if __name__ == "__main__": printMultipleValues("This", "is", "a", "program", "using", "multiple", "non-keyworded", "arguments", "in", "Python")
Output
Argument value 1 is: This Argument value 2 is: is Argument value 3 is: a Argument value 4 is: program Argument value 5 is: using Argument value 6 is: multiple Argument value 7 is: non-keyworded Argument value 8 is: arguments Argument value 9 is: in Argument value 10 is: Python
Explanation
The function “printMultipleValues” has an argument as *args. The * indicates that it can take multiple arguments and args is the argument name. The function is invoked. As a result, it passes the values to the function. All the values inside the function are published using the for loop.
Illustration of a function using **kwargs
def printMultipleValues(**kwargs): for key, value in kwargs.items(): print(f"{key} is {value}") if __name__ == "__main__": printMultipleValues(FirstPart = "Printing", SecondPart = "Using", ThirdPart = "**kwargs")
Output
FirstPart is Printing SecondPart is Using ThirdPart is **kwargs
Explanation
The function printMultipleValues takes a dictionary type as a parameter in the function. The dictionary contains key-value pair and through the for loop inside the function, each of the items in the dictionary is published with their individual key and value pair.
Benefits of using *args and **kwargs
We use *args and **kwargs to accept a changeable number of arguments that can be passed into the function that the user has created.
Also read: Use a mutable default value as an argument in Python
Leave a Reply