Opening Hours :7AM to 9PM
In Python, you can define a function that takes variable number of arguments. In this article, you will learn to define such functions using default, keyword and arbitrary arguments.
def myfun(name, msg): """This function myfuns to the person with the provided message""" print("Hello", name + ', ' + msg) myfun("sateesh", "Good morning!") Output Hello Sateesh, Good morning!Here, the function myfun() has two parameters.
>>> myfun("Sateesh") # only one argument TypeError: myfun() missing 1 required positional argument: 'msg' >>> myfun() # no arguments TypeError: myfun() missing 2 required positional arguments: 'name' and 'msg'
def myfun(name, msg="Good morning!"): """ This function myfuns to the person with the provided message. If the message is not provided, it defaults to "Good morning!" """ print("Hello", name + ', ' + msg) myfun("Kate") myfun("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 is required (mandatory) during a call.
def myfun(msg = "Good morning!", name): We would get an error as: SyntaxError: non-default argument follows default argument
# 2 keyword arguments myfun(name = "Bruce",msg = "How do you do?") # 2 keyword arguments (out of order) myfun(msg = "How do you do?",name = "Bruce") 1 positional, 1 keyword argument myfun("Bruce", msg = "How do you do?")
myfun(name="Bruce","How do you do?") Will result in an error: SyntaxError: non-keyword arg after keyword argPython Arbitrary Arguments Sometimes, we do not know in advance the number of arguments that will be passed into a function. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.
def myfun(*names): """This function myfuns all the person in the names tuple.""" # names is a tuple with arguments for name in names: print("Hello", name) myfun("Sateesh", "Luke", "Steve", "John") Output Hello Sateesh Hello Luke Hello Steve Hello JohnHere, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the arguments back.