def Welcome(name,msg): """This function provides the welcome the person with the provided message""" print("Welcome "+ name + ', ' + msg) greet("Ashish","Good morning!") Output Welcome Ashish, Good morning!Here, the function Welcome() has two parameters. Since, we have called this function with two arguments, it runs smoothly and we do not get any error. But if we call it with different number of arguments, the interpreter will complain. Below is a call to this function with one and no arguments along with their respective error messages.
>>> Welcome("Ashish") # only one argument TypeError: Welcome() missing 1 required positional argument: 'msg' >>> greet() # no arguments TypeError: Welcome() missing 2 required positional arguments: 'name' and 'msg'
Default ArgumentsFunction arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=). Here is an example.
def drawline(char, length = 80): i = 0 while i < length print(char,) i = i + 1In this function, the parameter name does not have a default value and is required (mandatory) during a call. On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional during a call. If a value is provided, it will overwrite the default value. Here are some valid calls to this function.
>>> drawline("*") #it will print * 80 times >>> greet("-",40) #it will print - 40 times
NoteThe non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:
def drawline(length = 50, "="): We would get an error as: SyntaxError: non-default argument follows default argument
Keyword ArgumentsWhen we call a function with some values, these values get assigned to the arguments according to their position. For example, in the above function drawline() when we called it as drawline("*",40), the value "*" gets assigned to the argument char and similarly 40 to length.
Keyword ArgumentsIf we want the variable number of arguments passed to the function or we do not know number of arguments in advance. Python allows to pass arbitrary number of arguments using list, tuple are called keyword arguments are defined by using asterisk (*) before the parameter name to denote this kind of argument.
def printnames(*names): # names is a tuple with arguments for name in names: print("Hello",name) print("Mahesh","Robin","Steve","Smith") Output Hello Mahesh Hello Robim Hello Steve Hello SmithHere, 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.