Understanding Common Default Values
For more information on concepts covered in this lesson, you can check out Python Booleans: Optimize Your Code With Truth Values.
00:00
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.
00:26
The integers 0
and 1
are common default values to use when a parameter’s value needs to be an integer. This is because 0
and 1
are often useful fallback values to have.
00:37
In the 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.
00:55
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.
01:23
This line of code will add an item to the shopping_list
dictionary with an empty string as a key and a value of 1
.
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
01:55
In this version, if no item is passed to the function, then the function sets the quantity to 0
.
02:08
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 True
.
02:22
When an if
keyword is followed by a truthy or falsy value, the if
statement will interpret these as True
or False
.
02:31
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.
02:46
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 null
value.
02:58
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.