Python Functions

A free video tutorial from Jose Portilla
Head of Data Science at Pierian Training
Rating: 4.6 out of 5Instructor rating
73 courses
3,537,373 students
Python Functions

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 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 def 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 to separate out different words. And then you have parentheses, a colon, and then you can have a docstring or a documentation string, which is essentially a multi-line comment which explains the function. And if you ever want to see the docstring of a function, you can do shift tab in your Jupyter 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 executed this at the 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 we 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 keyword 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 with functions, you're going to be returning the results. And to do that, we use the return keyword. 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 num1 and num2. And it's going to return num one plus num 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 function. So we can say result is equal to add, underscore, function, pass in whatever arguments or integers or numbers we want to add together. Here we have one and 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 results of multiple function calls. Let's explore more examples of using functions by loading a Jupyter notebook. All right. So as a quick overview, we have DF as the keyword. You're going to have a lowercase function name using snake casing and then as many arguments as you want. And arguments can actually have default values. You'll have your docstring, which is denoted by either triple single quotes or triple double quotes, and that allows you to create a multi-line comment or multi-line string here that is going to get ignored by your function. And then after the docstring, 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 DF keyword 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, this function has now been defined in the namespace of Python here in my notebook. So I can call reports and if I hit tab it will autocomplete to the whatever function I want. Keep in mind if I call the function with no parentheses, that means it just tells me hey, there's a function here. Report agent. We'll discuss what this main represents later on. But in order to actually execute the function, you need to pass in 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 report. 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 then 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 default arguments so we can add on a default argument to this name. Such as Jason. And we rerun this cell to redefine report as having a default argument. So now if I run report bond another time, it will 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 Sally 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. Colon. And we will now say print n1 plus N2. 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 results 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 result is equal to ad two 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 result, 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 redefine our function the add. N1 comma N2 and instead of printing out N1 plus N2, we are going to return N1 plus N2. And now if I say result is equal to AD two and four, I can check out that result is now equal to six. So that's the difference between using return and using print inside of function. And almost always you're going to be using return inside of functions. We're just using print 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 inside of a function saying something like function ran well 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 with 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 functionalize this by saying secret. Check is the name of my 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. We'll 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 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 s and it doesn't match exactly with what we were checking for here. So to fix that, what I could do is say dot 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 lowering case everything in that string before it runs the 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 doc string. So if you type out one, two, three quotes, either single or double, you'll notice that Jupyter Notebook automatically completes the second set of three. So here we can write in our doc 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 doc string input is a string output. Same string, but all vowels are converted 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 going to show that very quickly on an example string, if I pass in 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 will say for I comma letter in enumerate. My string. Remember that enumerate creates that list of tuple pairs. So we can say enumerate show 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 does. But we have these tuple unpacking of enumerate my string and then we're going to say for vowel. In and I'm going to create a list of vowels. We'll just do the basic ones here. A e i o u. So we'll just consider that as the vowel space for this problem. So now we're going to use a nested for loop. Notice 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 lowercase is equal to. A vowel. We're going to set the output. At that 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 E and O, so I would expect the result to look like h x ll x since what I'm doing here is I'm going through every letter in that string. Hello. Then I'm checking for every vowel an a e i o u if there's a match for that letter. And then we'll say if that letter, that lowercase matches that vowel, 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 lx x. What 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 is start with a simple example. We start with an empty string here. And then off of this we call the join method. So it's essentially a method off of a string. And then we pass in. This list of letters. We will say A, B, C and notice what we get back. We get back A, B, c. 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. So to make that more obvious, if I add two dashes here in my string and rerun this, now I get back two 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 X's 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 result. And get back that string that I wanted. H x. LX 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 we run this now. Check our results. So rerun these cells, we get back h x ll x. So let's quickly go over what's happening in this piece of code. In 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 the vowels, they're converted 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 this string as we saw earlier. Then we're going to use the enumerate 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 I 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, 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 this 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 construct the actual problem statements because more complex problems really need a functional grasp in order to create a real solution for them. Now that you 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.