A function that takes variable number of arguments in Python.
Example:
def tkd(name,msg):
print("Hello",name + ', ' + msg)
tkd("Raj","Good morning!")
Output:
Hello Raj, Good morning!
Here, the function tkd() has two parameters or arguments name and msg.
Variable Function Arguments
There are additional ways to define a function which can take variable number of arguments in Python. Which are below:
1. Python Default Arguments
Function arguments can have default values in Python. By using the assignment operator (=), we can define a default value to an argument.
def tkd(name, msg = "Good morning!"):
print("Hello",name + ', ' + msg)
tkd("Kate")
tkd("Bruce","How do you do?")
Output:
Hello Kate, Good morning!
Hello Bruce, How do you do?
In this function, the parameter name does not have a default value and the parameter msg has a default value of "Good morning!"
2. Python Keyword Arguments
Python allows functions to be called using keyword arguments. When we call functions in this way, the order or position of the arguments can be changed. Following calls to the above function are all valid and produce the same result.
# 2 keyword arguments
tkd(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
tkd(msg = "How do you do?",name = "Bruce")
# 1 positional, 1 keyword argument
tkd("Bruce",msg = "How do you do?")
We can see that mix positional arguments with keyword arguments during a function call. But having a positional argument after keyword arguments will result into errors.
Example
tkd(name="Bruce","How do you do?")
Output : SyntaxError: non-keyword arg after keyword arg
3. Python Arbitrary Arguments:
Python allows us to handle this kind of situation through function calls with arbitrary number of arguments. In the function definition we use an asterisk (*) before the parameter name to represent this type of argument.
Example:
def tkd(*names):
for name in names:
print("Hello",name)
tkd("Raj","Moni","Steve","John")
Output:
Hello Raj
Hello Moni
Hello Steve
Hello John
Commentaires