Default return Values
Now let’s take a look at how we can use the
or operator to provide a backup return value for some functions that might crash when evaluated with the main parameter value that you would like to give it.
max() are going to cause your program to crash—or more precisely, throw exceptions—if you provide them with an empty list.
And so if I create a list which is empty and try to find the maximum value in that list, I’m going to get an error message.
max() doesn’t like that and
min() doesn’t either. So we get an error, our program crashes. So, how can we prevent that? Well, let’s provide this method with a value to use in the event
lst doesn’t contain anything meaningful, and we can use the
or operator to do that.
So if I say
or—and now let me create a new list with a value that I would recognize as not being meaningful to my data.
So maybe all of my values in my lists are positive and if I do something like
[-1], a list containing a single value of
-1, this will tell me that there wasn’t anything meaningful in the real parameter that I wanted to use,
And so I can write code after finding the minimum value of my
lst to check for this
-1 to say, “Well, there really wasn’t a minimum value because
lst was empty.” And so now since
min() is going to use the second operand and return that value.
And the good news is the program doesn’t crash, we don’t generate an error. We can write an
if statement to check for this and if we got a value back other than
-1, then we know that our list had meaningful data and we did get the true minimum value from that. And if we did get the
-1 back, we would write code to indicate not to use that particular minimum value.
In your next lesson, you’ll see how you can use the
or operator to help you work with mutable arguments to functions that you write.
Become a Member to join the conversation.