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