For more information on concepts covered in this lesson, you can check out Python Booleans: Optimize Your Code With Truth Values.
Understanding Common Default Values
Common Default Argument Values. In the examples you’ve seen previously, you used the integer
1 as a default value in one case and the Boolean value
True in the other. These are common default values you’ll find in function definitions. However, the data type you should use for default values depends on the function you are defining and how you want the function to be used.
1 are common default values to use when a parameter’s value needs to be an integer. This is because
1 are often useful fallback values to have.
add_item() function you wrote earlier, setting the quantity for a new item to
1 is the most logical option. However, if you had a habit of buying two of everything you purchase when you go to the supermarket, then setting the default value to
2 may be more appropriate for you.
When the input parameter needs to be a string, a common default value to use is the empty string (
""), as seen on-screen.
01:08 This assigns a value whose data type is a string, but doesn’t put in any additional characters. You’ve modified the function so that both parameters have a default value, and therefore the function can be called with no input parameters.
This line of code will add an item to the
shopping_list dictionary with an empty string as a key and a value of
01:35 It’s fairly common to check whether an argument has been passed when the function is called and run some code accordingly. You can change the function to do this, as seen on-screen
In this version, if no item is passed to the function, then the function sets the quantity to
The empty string has a falsy value, which means that
bool() of it returns
False. Whereas any other string will have a truthy value and will return
if keyword is followed by a truthy or falsy value, the
if statement will interpret these as
You can read more about truthy and falsy values in this Real Python tutorial. You can therefore use the variable directly within an
if statement to check whether an optional argument was used.
Another common value that’s used as a default value is
None. This is Pythonic way of representing nothing, although it is actually an object that represents the
You’ll see an example of when
None is a useful default value to use in the next section.
Become a Member to join the conversation.