Default Values for Variables
00:00
Let’s take a look at some examples where we might use the word or
to assign a default value to a variable. We might have a condition where a variable x
needs to be one of two values and if neither of those values evaluate to be True
, we want to indicate that with some special value for x
.
00:23
Let’s look at a situation where x
is supposed to be a collection we’re supposed to process and we know that variable a
is supposed to be a list to work on and variable b
, if we don’t have a list, is supposed to be in a dictionary.
00:40
But in the event both of those are empty, we would want to let x
be a value to indicate that. So we might use x = a or b or None
, and then we can have a test later in the program to see if the value of x
is meaningful or whether it has no value at all.
01:07 Another situation, here in the second line, is that there is a default value that we always use for something unless through input or some other action a different value to be used is given.
01:22
For example, say a calendar. We know many calendars begin their week on a Sunday, so we might create a variable called default
, which is equal to the string "Sunday"
.
01:35
And there might be another process where somewhere within the program, they’re allowed to provide a value for a
which might be a different day of the week.
01:42
Some people choose Mondays to start their week. So if we say y = a or default
and they’ve given a value for a
, we’ll use that.
01:57
On the other hand, if they didn’t provide a value for a
, we somehow indicate that with an empty string (""
). And then when we say y = a or default
, a
evaluates to be False
, so whatever is in default
is returned.
02:17
In this case, we’ll have our workweek beginning on 'Sunday'
.
Become a Member to join the conversation.