Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
Functions can be used for a number of purposes and some times those purposes require the values be returned from the function. Let's take a look at how we return values from functions in Python. We start by making a working copy of functions.py. We will name it functions-working.py and we'll open that up and there we have our little test function. How about instead of printing this if we simply return it and then print it from up here and say print(testfunc())? So we'll save this and run it and there is our string.
So all this function is doing is it's returning this string. The return keyword is the way that the values are written. The value itself comes after Return and it can be any type. We can return a number. Save that and run it and there is our number. We can return an object, say range(25), and that will return a range object. We'll save this and run it. And there is the range object.
In fact, that range object is now usable as an iterator. So if I say for n in testfunc(): print(n, end=' '). Save that and run it. We've got that whole range. And you'll notice that just like a range is supposed to, it's non-inclusive and it does not include that last 25th object.
So you can really return any object from a function using the return statement and that's done simply with return and then the object.
Get unlimited access to all courses for just $25/month.Become a member