Python Functions

Jose Portilla
A free video tutorial from Jose Portilla
Head of Data Science, Pierian Data Inc.
4.6 instructor rating • 32 courses • 2,261,127 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 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 the 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 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 underscores to separate different words. And then you have parentheses a colon and then you can have a docstring or documentation string which is essentially a multi-line comment which explains the function. And if you want to see the docstring of a function you can do shift tab and you choose 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 executed 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 it 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 and 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 the 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 number one and number two. And it's going to return one plus them to. 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 function so we can say result is equal to add underscore function pass and whatever arguments are 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 result of multiple function calls. Let's explore more examples of using functions by loading a all right. So a quick overview. We have DMF as the keyword. You're going to have a lowercase function name using snake casing and then as many arguments as you want in arguments can actually 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 comments 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 of a really simple example called Report agent. So notice I use the F 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 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 a function with no parentheses that means it just tells me hey there's a function here. Report agent will discuss what this maner 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 it's shown 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. It could also just use concatenation But this report function what it does is it takes in the primary name and it's going to say reporting whatever you passed in. So if it's just call report with no parameter ill actually induce an error and it says type error report is missing. One required positional arguments name so it needs the name in order to run because it has no default value for name. So if we try saying bond they'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 the cell to read the fine report as having a default argument. So now if I run a report bond another time they'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 it 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 they'll 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 did this we can use the return keyword. Let's revisit our function of adding two numbers together will create a function called ADD and it takes in two promoters and one and two colon and we will now say Prince and one plus and 2. So if I call add to 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 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 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 read the fine R function D. Add in 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 four I can check out that result is now equal to 6. So that's the difference between using return and using print inside a function and almost always you're going to be using return inside of functions. We're just using print's 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 a result again. Now let's go ahead and solve some problems of functions. Functions are a core building block for scripts and code. So we're going to show you some more examples. Let's imagine you 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 he can functionally is this by saying secret check is the name of my function. It takes 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 were able to just plainly read this out by writing a simple syntax secret in my string. So let's run this. We'll say secret check and I will 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 of what we were checking for here. So to fix that what I could do is say lowercase everything in the string so I rerun the cell to find that and it will now get if I run this secret check this is true because it's lowering 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 the 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 docstring. So if you type out one to 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 docstring will 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 whip's say output and we're just going to say do nothing here. So if we take a look at coachmaker and I do shift tab you'll notice that I can now see the docstring input is a string output same string Brul vows. Convert it to an X. So this documentation's string is the exact same thing that we wrote here. So there's 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'll 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 really quickly on an example string by pass and list in 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. First then we'll say for I comma a letter in enumerates my string. Remember that enumerate creates that list of tuple pairs. So we can say numerators 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 discuss this back when we talk about useful operators. So you can review that lesson in case you want to see what enumerate those but how these tuple and packing of enumerate my string. And then we're going to save for a vowel. In and I'm going to create illest avowals. Just do the basic once here a. E I O U. So I'll just consider that as a yvel 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 or we're going to do is say if the letter turned lowercase is equal to a vowel we're going to set the output at that index. Equal to X. Let's test out this coachmaker that we just created. We're going to say result is equal to code maker. And we're going to pass on some string to a simple one like hello and we can see Hello has two vowels E.A.. 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. H E I O U. If there's a match for that letter and then we'll say if that letter that lowercase match to 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 Liszt's H x l l x or would be nice though. 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 an this list of letters who will say ABC and notice when 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 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 X's here and you'll see that in between each of these elements we get back whatever string we want to join them together by. So that means if might have an empty string I just join everything together. So instead of passing that list I could just pass result and get back that string that I wanted. H x x. So let's actually return this then. So we'll see output here if we come back up remember output is still list at this point. We're going to say join output. And in fact we don't technically need to reassign that here. You could just optionally return this by itself. So if we run this now check our results. So rerun the cells we get back H. X x. So let's quickly go over what's happening in this piece of code and this function we're saying coachmaker takes in a string. We have a documentation string describing what our goal is here. The IMPA is a string. The output is that same string but for all of L's are converted to an X or a 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 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 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 II is equal to x so reassign that output 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 key word to indicate that you're not going to do anything else. So it would be if there was a match re-assignment 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 the 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 at the next lesson where we describe the tasks you need to solve with functions.