Default values for parameters
It is possible to define a default value for function parameters. This is useful in scenarios when a function is called without an argument – these default values will be assigned to function arguments. However, if an argument is provided during the function call, Python will use the explicitly passed values for the argument.
The default parameters are defined in the function definition. Consider the following example:
def describe_me(name="Tuna", gender="M", website="geek-university.com"): print(name, gender, website) describe_me()
The output:
>>> Tuna M geek-university.com <<<
Since no arguments were passed when the function was called, the three arguments were assigned by default.
Now, consider what happens if we pass all three arguments when calling the function:
describe_me('Tanya', 'F', 'tanya.com') >>> Tanya F tanya.com >>>
As you can see from the output above, the default arguments were replaced by the ones specified in the function call.
But what if we have only a single parameter with a default value? Let’s say that all users should have the same default website – geek-university.com, if not explicitly stated otherwise during the function call. Well, we can explicitly specify the two arguments in the function call using their keywords:
def describe_me(name, gender, website="geek-university.com"): print('Name:', name, '\nGender:', gender, '\nWebsite:', website) describe_me(name='Tanya', gender='F') >>> Name: Tanya Gender: F Website: geek-university.com >>>
As you can see from the output above, the website argument wasn’t specified in the function call so Python used the default argument (geek-university.com) specified during the function definition. The other two arguments (name and gender) were specified so the defaults weren’t used.
When keyword arguments are used, the order of arguments is not important. In example above, I could have written describe_me (gender=’F’, name=’Tanya’) and the code would work fine. However, the order is important if you are using positional arguments. I could have called the function like this:
describe_me('Tanya', 'F') >>> Name: Tanya Gender: F Website: geek-university.com >>>
Python now matches the first passed argument with the first parameter specified in the function definition and the second passed argument with the second specified parameter. Since the third argument wasn’t specified, the default value is used for the website. However, consider what happens when I make this call:
describe_me('F', 'Tanya') >>> Name: F Gender: Tanya Website: geek-university.com >>>
As you can see from the output above, Python correctly used the default parameter for the website. However, the name and gender parameters have been swapped.