Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Default return Values
00:00
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.
00:16
Methods like min() and max() are going to cause your program to crash—or more precisely, throw exceptions—if you provide them with an empty list.
00:26
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.
00:43
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.
01:01
So if I say min() of lst, or—and now let me create a new list with a value that I would recognize as not being meaningful to my data.
01:12
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, lst.
01:30
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.”
01:42
And so now since lst is False, min() is going to use the second operand and return that value.
01:53
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.
02:10
And if we did get the -1 back, we would write code to indicate not to use that particular minimum value.
02:19
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.