In the last lesson, we looked at how to use positional arguments to provide values to the parameters of a function. In this lesson, we’re going to take a look at using keyword arguments to provide values to those same parameters. When you call a function, instead of just providing a value you, can use the notation
<name> is the name of the parameter and the
<value> is the expression or value you would like that specific parameter to have. In doing this, you no longer need to maintain the order of the parameters that were given in the header of the function definition.
00:40 Since you’re specifying each one by name, Python will know which argument to use for each parameter. So, let’s use the same function from the last lesson and now let’s take a look at using keyword arguments to specify values.
01:43 So when we make this function call, the appropriate values are used for their respective parameters and the function behaves the way it should. You still have to be mindful of the number of parameters a function is expecting.
You have to be mindful of the actual names of the parameters. So, for example, if I say
'bananas', and I say
cost=1.74, I’m going to get an error message because there is no parameter
There’s a parameter
price, and in our minds, price and cost are roughly the same thing, but Python just sees this as an identifier and it looks at the name
cost and it doesn’t have a parameter named
cost up here, so it doesn’t know what to do with that. And again, if you leave out a parameter,
I then cannot go back and use a positional argument. So once I start using keyword arguments, I must do that to completion. We get an error that we can’t call it that way, so if I want to do this correctly, I have to say
price= and then it’s going to let me do that.
Become a Member to join the conversation.