Assigning Default Values
If you pass an argument corresponding to
quantity when you call the function, then that argument will be used as the value for the parameter. However, if you don’t pass any argument, then the default value will be used.
1 in this case. Parameters with default values can’t be followed by regular parameters. You’ll see more about the order in which you can define parameters later on in this course. The function
add_item() now has one required parameter and one optional parameter.
In the code example just seen, you call
add_item() twice. Your first function call has a single argument, which corresponds to the required parameter
item_name. In this case,
quantity defaults to
1. Your second function call has two arguments, so the default value isn’t used in this case.
01:47 You can also pass required and optional arguments into a function as keyword arguments. Keyword arguments can also be referred to as named arguments. You can now revisit the first function you defined in this course and refactor it so that it also accepts a default argument.
Now when you use
show_list(), you can call it with no input arguments or pass a Boolean value as a flag argument. If you don’t pass any arguments when calling the function, then the shopping list is displayed by showing each item’s name and quantity.
03:04 You should avoid using flags in cases where the value of the flag alters the function’s behavior significantly. A function should only be responsible for one thing. If you want to flag to push the function into an alternative path, you may consider writing a separate function instead.
Become a Member to join the conversation.