Parameters can be assigned values in the function headers—that’s the top line where the function definition starts. If, after a parameter name, you follow it with an equal sign (
=) and then a value, that becomes the default value for that parameter and it becomes an optional parameter for someone trying to use or call your function.
00:34 If they don’t specify an argument for that particular parameter, then the one you supplied in the header is the one that’s going to be used. This gives us the notion of default parameters, or optional parameters.
Let’s take a look at defining our function—the same one we’ve been using before—in a slightly different way. We’re going to define our function
f(). It’s going to have a parameter
qty (quantity), and it’s going to have a default value of, say,
6. The second parameter we’ll still call
item, but it will have a default parameter of
The body of this function is going to be the same that we’ve seen before. We’re simply going to print
item, and then conclude the sentence and say that “Those many items cost…” and then express the
price as a two-digit decimal number.
02:48 And because I have specified default values for all three parameters, I don’t have to supply any arguments! And in that case, all three of the parameters will get their values from the function header and they will use the default values.
04:06 If there are three given in the function header, then three must be supplied in the order that they’re expected. Keyword arguments must agree with the parameter names, but they can be used in any order. And of course, if you’re not using default parameters, they too must agree with the number of parameters a function is expecting.
04:28 Default parameters allow some arguments to be omitted when the function is called. Again, for values that often don’t change from one function call to the next but may sometimes be different, that would be a good use of a default parameter, a default value for that type of parameter.
Become a Member to join the conversation.