Python Default Arguments
Python Default Arguments
Output
Hello Monica, Good morning!
Since, we have called this function with two arguments, it runs smoothly and we do not
get any error.
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.
We can provide a default value to an argument by using the assignment operator (=).
Here is an example.
In 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.
Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
This means to say, non-default arguments cannot follow default arguments. For
example, if we had defined the function header above as:
Python allows functions to be called using keyword arguments. When we call functions
in this way, the order (position) of the arguments can be changed. Following calls to the
above function are all valid and produce the same result.
As we can see, we can mix positional arguments with keyword arguments during a
function call. But we must keep in mind that keyword arguments must follow positional
arguments.
Having a positional argument after keyword arguments will result into errors. For
example the function call as follows:
In the function definition we use an asterisk (*) before the parameter name to denote
this kind of argument. Here is an example.
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John")
Run
Powered by DataCamp
Output
Hello Monica
Hello Luke
Hello Steve
Hello John
Here, 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.