Python Functions

Jose Portilla
A free video tutorial from Jose Portilla
Head of Data Science, Pierian Data Inc.
4.6 instructor rating • 36 courses • 2,504,627 students

Lecture description

Expand your knowledge of Python 3 by learning about some more advanced Python functionality. 

Learn more from the full course

Complete Python 3 Masterclass Journey

Master Python 3! Use story based learning to go from a beginner to being able to create real programs with Python!

10:42:04 of on-demand video • Updated September 2019

  • Create your own Python scripts to automate tasks.
  • Read CSV Files with Python.
  • Be able to work with PDF files in Python.
  • Manipulate images with Python.
  • Learn how to create functions with Python.
  • Use Object Oriented Programming with Python.
  • Send and receive emails automatically with Python.
  • Decryption , Encryption, and Hashing with Python.
  • Plot geographical points on Google Maps with Python.
  • Read files and apply regular expressions with Python.
  • Scrape websites for information using Python.
English [Auto] Welcome back, recruit, today we'll be discussing functions. Creating clean, repeatable code is a key part of becoming an effective programmer, functions allow us to create blocks of code that can easily execute multiple times without needing to constantly rewrite the entire block of code. Instead, you just call the function name itself. We've already explored a built in functions in Python, such as the range function. Let's explore the syntax for creating our own functions. The syntax is the following, you start off with the DFI keyword, allowing you to define the function, then you have the name of the function and typically the name is lowercase with snake casing. That is the use of underscores the Cypriot different words. And then you have parentheses, a colon, and then you can have a dark string or documentation string, which is essentially a multiline comment which explains the function. And if you ever want to see the dark string of a function, you can do shift tab and you chip in a notebook. And this is what pops up as an explanation for users who intend to execute your function. And then you have here we can see in blue just whatever code you want to happen when the function executes. So here we can see in purple at the very bottom what would happen if we execute this command line. We would call the name of the function and then we get back. Hello. It prints out. Hello. You can also provide parameters to functions here, you can see a very similar example, except this time it's taking a parameter or an argument called name, and then it's going to print hello and concatenate it with the name. So if we said name a function pass in the string hopper, it will say, Hello, Hopper. Typically, we use the return key word to send back the result of the function instead of just printing it out. So if we take a look at the function we just saw here, we're really just printing out results. Usually when you're writing the functions, you're going to be returning the results. And to do that, we use the return. Key word return allows us to assign the output of the function to a new variable. Here we can see another example showing this use of return keyword. We've created a new function called add underscore function, and it takes in two parameters or two arguments, number one and number two. And it's going to return number one, plus them two. So when you call this function, instead of just calling it and expecting something to be printed out instead, what we can do is we can assign a variable equal to whatever gets returned from this, add a function so we can say the result is equal to add, underscore, function, pass and whatever arguments or integers or numbers we want to add together here we have one or two being added together and then we can print the result to three. And that allows you to actually use variables in order to save the result of multiple function calls. Let's explore more examples of using functions by loading a Jupiter notebook. All right, so as a quick overview, we have D.F. as the key word, you're going to have a lowercase function name using snake casing and then as many arguments as you want and arguments can actually default values. You'll have your dog string, which is denoted by either triple single quotes or triple double quotes. And that allows you to create a multiline comment or multiline string here that is going to get ignored by your function. And then after that string, you can write code that does whatever you want. So let's build up many more examples of this. We'll start off with a really simple example called report agent. So notice I use Dfki word and everything is syntax highlighted here, space, whatever you want the name of your function to be. And in this case, this function will not take any parameters. And we're just going to print out. Report agents, so I do shift enter to run this, and once I run, this dysfunction is now being defined in the name space of Python here, my notebook so I can call reports. And if I hit tab, there will autocomplete to the whatever function I want. Keep in mind, if I call a function with no parentheses, that means it just tells me, hey, there's a function here, report agents. We'll discuss what this man represents later on. But in order to actually execute the function, you need to pass an open and close parentheses. So this actually calls the function to execute. And here we can see the result report agent. So now let's show an example of passing in arguments or parameters. So we're going to create another function called reports. It takes in a name. And it's going to print out. Reporting and we'll just use print formatting here, you could also just use concatenation, but this report function, what it does is it takes in the parameter name and it's going to say reporting whatever you passed in. So if I were to just call report with no parameter, it'll actually induce an error and it says type error report is missing one required positional argument name. So it needs the name in order to run because it has no default value for name. So if we try saying Bond, it'll say reporting bond. Let's look at another example that uses Diffa arguments so we can add on a default argument to this name. Such as Jason and we rerun the cell to read the fine report as having a default argument. So now if I run report bond another time, it'll still say reporting bond. But since report has a default value for name, it will default to that value. If you happen to forget to provide one or if just on purpose, you don't provide one. So if you write out report now run it. It will default to report Jason, unless you overwrite it to something else such as report Sallie and it will say Reporting Sally. So far all of our functions have only been printing results. But what if we actually wanted to save the actual results of the function to another variable? To do this, we can use the return keyword. Let's revisit our function of adding two numbers together. We'll create a function called ADD and it takes in two parameters. And one and two. Colin. And we will now say Prince and one plus and two. So if I call add two, comma three, it's going to add them together and print out the number five, if I wanted to save the result of this. I would not be able to because I'm only printing it out, I'm not actually returning it. So I will say the result is equal to add to comma three notice I get back five, but if I call my result, I don't get anything. And if I check the type of my results, I get back none type. This is because this function is only set to print things out. It's not set to actually return objects to be saved, which is why we still see a five here. It's being printed out, but result isn't having anything assigned to it. In order to assign something, we need to use the return keyword. Let's show you now how you can add that in. We will read the fine function, the ad. And one comma and two, instead of printing out and one plus two, we are going to return and one plus and two. And now if I say result is equal to add. Two and a four I can check out, that result is now equal to six, so that's the difference between using return and using print instead of function. And almost always you're going to be using return inside of functions. We're just using prints before to basically show you the syntax of a function whenever you're using functions. However, more likely than not, you're going to be having a return as your final statement. However, it is common to see print statements instead of a function saying something like Function Cranwell or whatever have you. So you can see that the function ran well. That way you can understand what's happening, but you'll also be able to see your result again. Now let's go ahead and solve some problems at functions. Functions are a core building block for scripts and code. So we're going to show you some more examples. Let's imagine we wanted to write a function that returns a boolean that is true or false, indicating if the word secret is in a string. So, again, the problem we're trying to solve here is, is the word secret in a string so we can functionalized this by saying secret. Check is nameI function, it takes in some string, my string, and then what it's going to do is it's going to return. If secret, that string is in. My string here, we can see a really nice example of why Python has such high readability, we're able to just plainly read this out by writing simple syntax secret in my string. So let's run. This will say secret check and we'll say this. Is a secret and it says true, and if I take away the word secret. This is a lie. It returns false, however, if I were to say a secret check and it says this is a and we capitalize secret, it's going to say false because this string secret has an uppercase case and it doesn't match exactly what we were checking for here. So to fix that, what I could do is say that lowercase everything in the string. So I rerun the cell to redefine that, and I will now get if I run this secret check, this is true because it's lower in case everything in that string before it runs a check to see if secret is inside that string, keep those sort of things in mind when you're trying to solve problems with functions. Let's look at one more example. We're going to do a code maker function and this function will take in a string name and replace any vowels it sees with the letter X as a way of kind of hiding out the real message inside of it. So we will say code maker. And it takes in my string. And let's give it a documentation string or a dock string, so if you type out one, two, three quotes, either single or double, you'll notice that you put a notebook, automatically completes the second set of three. So here we can write in our dock string. So we'll say input is a string output. Same string, but all vowels are converted to an X, so let's just look at this right now. We're going to say output and we're just going to say. Do nothing here. So if we take a look at code maker and I do shift tab, you'll notice that I can now see the dock string input is a string output, same string grovels, convert it to an X. So this documentation string is the exact same thing that we wrote here. So this is a nice way for other people who are using your code to understand what your intentions are when you were creating this function. Now let's actually fill this out so it does what it describes. So let's start by doing the following we're going to create. A variable output that at the very end of all this, we're going to return the output. And we will say output is equal to list my string, so this allows us to take a string and convert it quickly to a list. So I'm just going to show that very quickly on an example, string bypass and list and the string example, it quickly converts this into a list where every character is now an element in that list. So that's what output is going to look like at first. Then we'll say for Ikoma letter in enumerates. My string, remember that enumerate creates that list of tuple pairs so we can say enumerates, showed the example here and let's actually pass this to a list so I can see what this is actually looking like. It's basically having an index count along with the character. So, again, we discussed this back when we talked about useful operators. So you can review that lesson in case you want to see what enumerate those. But we have these tuple in a packing of enumerate my string and then we're going to say four vowel. In and I'm going to create a list of avowals, we'll just do the basic ones here a e i o u so we'll just consider that as a valid space for this problem. So now we're going to use a nested for loop the indentation here. So for every index and letter in the string and for every vowel in this list, what we're going to do is say if. The letter. Turn lower case is equal to. A vowel. We're going to set the output. At the index. Equal to X, let's test out this code maker that we just created, we're going to say result is equal to code maker and we're going to pass in some string. Let's do a simple one like hello. And we can see hello has two vowels know. So I would expect the result to look like h x, l, l x, since what I'm doing here is I'm going through every letter in that string. Hello that I'm checking for every vowel and a IOU if there's a match for that letter. And then we'll say if that letter that lowercase matches that well, go ahead and replace that particular letter in the list with X. So if we run this. And we check the results, we get back a list H x, l, l x would be nice, though, is instead of getting back this list, if we actually got it back as a string to do that, we can use the join function or the join method off a string. Let me show you how that works and then we can implement it inside of this function. So what we're going to show you start with a simple example, we start with an empty string here and then off of this we call the joint method. So it's essentially a method off of a string and then we pass in. This list of letters. Who will say ABC, I notice when we get back, we get back ABC. So the way this works is you take in a list here and you're going to join every element in this list together with whatever the string is in between them to make that more obvious. If I had two dashes here in my string and rerun this, now I get back to dashes in between every string or every element in this list, meaning we can play around with this. We can add in a bunch of things, like a bunch of Xs here, and you'll see that in between each of these elements, we get back whatever string we want it to join them together by. So that means if I have an empty string, I just join everything together. So instead of passing that list, I could just pass in results and get back that string that I wanted X X. So let's actually return this then. So we'll say output here if we come back up. Remember, output is still a list at this point. We're going to say. Join. Output and in fact, we don't technically need to reassign it here, you could just optionally return this by itself. So if you run this now. Check our results, so we run these cells, we get back h, x, l, l, X.. So let's quickly go over what's happening in this piece of code and this function. We're saying code maker takes in a string. We have a documentation string describing what our goal is here. The input is a string, the output is that same string. But for all of us to convert it to an X, our first step so that we can easily iterate and do reassignments is we convert or we create an output called list of my string, which essentially is creating a list out of the string, as we saw earlier. Then we're going to use the innumeracy operator or enumerate function on our string and saying for every index position and every letter in that, then we have a nested for loop inside of that, that for every letter and for every vowel in this list of vowels, go ahead and check if that letter, when it's lowercase, matches up with that vowel. All this essentially means is for every letter, we're going to do five checks against that letter to see if it matches a vowel. And then we're going to say output of EI is equal to X, so reassign that output to X if there happens to be a match here. The other thing we could do is if you wanted to just for readability, you could say else and then use the pass keyword to indicate that you're not going to do anything else. So it would be if there's a match, reassign it or else pass. Don't do anything that's optional here. You don't actually really need it. Otherwise the code will still run the same way if you have it or not. At the very end, we have that list for the output and we're going to join the output together using the string right here. And because the string is empty, we're essentially just joining it together, every element in that list. All right. That's the basics of functions. And now that you understand functions as some of the basic building blocks of larger scripts, it really opens up the possibilities of the type of problems you can solve with Python. Earlier, you were seeing in your field readiness exams that we had to constrict the actual problem statements because more complex problems really need a functional grasp in order to create a real solution for them. Now, to understand how functions work, we're actually going to give you a list of tasks coming up next to solve with functions. So we'll see you at the next lesson where we describe the tasks you need to solve with functions.