Keyword ParametersΒΆ

In the previous section, on Optional Parameters you learned how to define default values for formal parameters, which made it optional to provide values for those parameters when invoking the functions.

In this chapter, you’ll see one more way to invoke functions with optional parameters, with keyword-based parameter passing. This is particularly convenient when there are several optional parameters and you want to provide a value for one of the later parameters while not providing a value for the earlier ones.

The online official python documentation includes a tutorial on optional parameters which covers the topic quite well. Please read the content there: * Keyword arguments

Don’t worry about the def cheeseshop(kind, *arguments, **keywords): example. You should be able to get by without understanding *parameters and **parameters in this course. But do make sure you understand the stuff above that.

The basic idea of passing arguments by keyword is very simple. When invoking a function, inside the parentheses there are always 0 or more values, separated by commas. With keyword arguments, some of the values can be of the form paramname = <expr> instead of just <expr>. Note that when you have paramname = <expr> in a function definition, it is defining the default value for a parameter when no value is provided in the invocation; when you have paramname = <expr> in the invocation, it is supplying a value, overriding the default for that paramname.

To make it easier to follow the details of the examples in the official python tutorial, you can step through them in CodeLens.


As you step through it, each time the function is invoked, make a prediction about what each of the four parameter values will be during execution of lines 2-5. Then, look at the stack frame to see what they actually are during the execution.


Note that we have yet another, slightly different use of the = sign here. As a stand-alone, top-level statement, x=3, the variable x is set to 3. Inside the parentheses that invoke a function, x=3 says that 3 should be bound to the local variable x in the stack frame for the function invocation. Inside the parentheses the define a function, x=3 says that 3 should be the value for x in every invocation of the function where no value is explicitly provided for x.

Check your understanding

Next Section - Exercises