In the last lesson, we looked at functions that return some sort of value.
We created a function called format_name that returned a string. In this
lesson
let's see what happens when a function has more than one return statement.
When the computer encounters a line that has the word return on it,
then it knows that this line is the end of the function.
If I add a line of code after the return keyword, notice what happens when I run
this code. It doesn't ever get executed.
And this has because the return tells the computer that this is the end of the
function and you should now exit the function.
You can actually have multiple return keywords within the same function,
and you can even have a empty return keyword.
So just the return keyword without anything afterwards.
So for example,
we could check whether if the fname is equal to an empty string or the lname
is equal to an empty string. So this case,
it means that when we called it format name, maybe we didn't give it any inputs.
For example, let's say that instead of just calling the function as it is,
we actually used the input function.
So what is your first name and what is your last name?
Now
what happens is it'll ask us for a input and it will take these two inputs
and then call that function and return the formatted version to be printed.
So now in this case, it's possible that we might have just not given it
a first name or not given it a last name and it probably shouldn't go through
these lines of code. But at the moment, it's still running this function
trying to get the title case from the empty string and then printing it.
And I can prove this to you by just adding an extra word in here.
So again, empty first name, empty, last name,
and then it's print result and then of course nothing.
How can we get it to bypass the rest of the code if the user typed in an empty
first name or last name? Well,
we could use what I mentioned before, an early return.
So we could just write return without anything afterwards
and this is going to escape the function.
So it's basically going to terminate the function early.
Now this time, if I leave an empty first name and last name,
you'll see it prints none because there is no output from this to print.
Now, of course,
it's probably safer to actually return something that tells the developer what's
actually going on so we can give a meaningful message,
like return, something like this.
So this way we can catch the cases when something is not quite right and then
exit our function instead of wasting time for it to continue working on
something that we don't want it to do.
We've covered a number of things in today's lesson
and I want you to combine this with your existing knowledge to tackle the
challenge in the next lesson
to get to grips with this concept of functions with inputs and with outputs.