Default Values for Variables
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
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.
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.
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.
Become a Member to join the conversation.