Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

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. 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, orand 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.” 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. 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.