# Python Tutorial for Beginners 8: Functions

## Метаданные

- **Канал:** Corey Schafer
- **YouTube:** https://www.youtube.com/watch?v=9Os0o3wzS_I
- **Дата:** 17.05.2017
- **Длительность:** 21:47
- **Просмотры:** 1,295,473
- **Источник:** https://ekstraktznaniy.ru/video/12617

## Описание

In this Python Beginner Tutorial, we will begin learning how to write functions. Functions are one of the most important things to learn in Python Programming and will take us to the next level. We will learn how to create/define functions, how to pass in arguments, and also how to return values. Let's get started.

The code from this video can be found at:
https://github.com/CoreyMSchafer/code_snippets/tree/master/Python-Functions

Watch the full Python Beginner Series here:
https://www.youtube.com/playlist?list=PL-osiE80TeTskrapNbzXhwoFUiLCjGgY7

Scope Video: https://youtu.be/QVdf0LgmICw


✅ Support My Channel Through Patreon:
https://www.patreon.com/coreyms

✅ Become a Channel Member:
https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join

✅ One-Time Contribution Through PayPal:
https://goo.gl/649HFY

✅ Cryptocurrency Donations:
Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
Litecoin Wallet - MPvEBY5fxGkmPQgocf

## Транскрипт

### Functions []

hey there how's it going everybody in this video we'll be learning about functions now functions are basically some instructions packaged together that perform a specific task so let's create our first function and see why these are so beneficial Now to create a function we'll use the defa keyword which I believe stands for definition and let's just make a simple function here to get started I'll call this hello Funk now we have parentheses there because that is where our parameters will go when we add those in but we don't have any parameters just yet so that will be empty for now it is possible to write a function and not have any code in it but we can't leave it completely blank uh but if we want to fill this function in later then we can use this

### Pass keyword [0:43]

pass keyword and basically that pass keyword is saying that we don't want to do anything with this for now but it won't throw any errors for leaving it blank so if we want to run our function then we can just say hello Funk and put in these parentheses and we need to add those parentheses after the function in order to execute it if we don't have those parentheses there then it'll be equal to the function itself um so let's actually see what that looks like so I'm going to print out that hello function without the parentheses in place uh which means that we're not executing the function so let me run that and we can see when we printed that out that it prints out that this is a function in a certain location in memory but it didn't execute the function so to execute it then we add in these parentheses so now if I run this then now it just gives us none because we're not doing anything with this function yet and it doesn't have a return value so let's go ahead and put some code into our function so first we'll just put in a print statement and we'll just print out some text that says hello function with an exclamation point and now that we're actually running that print statement from within the function we don't need to print out that executed function we can just execute that function and it should run that print statement so we'll run that so we can see that we executed our function here it came within our function and ran our print statement now one benefit of functions is that they allow us to reuse code without repeating ourselves so let's say for example that we had to print out some text in several locations throughout our program so it might look something like this so let me copy this and I'll comment out our uh function execution for now and I'm just going to paste this in about four times so now if we run this then as we expect it prints out our four messages now imagine our boss came to us and told us that uh the text was a little bit off and that we didn't want to have an exclamation point at the end of the string well the way that we have it now we'd have to come in here and change all of those manually so I'd come in and change all these man messages to have a period instead now that was only four changes to make there but in some instan that can be in hundreds of locations in multiple different files so that's the first benefit of functions it allows us to put code with a specific purpose into a single location so instead of printing those four statements uh what we can instead do is run our function four times so I will remove that and uncomment our function and we're going to execute this four different times so now if we run that then we can see that it ran our function four times and executed our print statement four different times but now if our boss came to us and asked us to remove that exclamation point then it doesn't matter if this is spread out over a 100 different lines or 100 different locations we can just update it in this one spot so I can change this to a period and now if we run this then we can see that those changes are seen everywhere that the function is called now this is called keeping your code dry which stands for don't repeat yourself it's a common mistake for people new to programming to repeat the same things throughout their code when really they could either put their code into certain variables or functions so that it's in a single location so we saw earlier that since we aren't returning anything from our function uh it was actually equal to none so what does it mean for uh our function to return something now this is where functions become really powerful because it allows us to operate on some data and then pass the result to whatever called our function so instead of printing this string hello function within here let's instead return this okay so what does this mean

### Executing functions [4:35]

exactly this means that when we execute our function it's actually going to be equal to our return value so these executed functions here are actually equal to the string hello function so right now if we run this then it doesn't give us any results because it's just a string that we're not doing anything with but if instead we print this so me print that executed function and if we run that then we can see that it prints out our string so basically think of a function as a machine that takes input and produces a result when you execute a function you can think of it almost like a black box you don't need to know exactly how it's doing what it's doing you're mainly concerned about the input and the return value so in this simple example here we don't have any input and we can see that the return value is a string um now don't get me wrong it's useful to know what a function is doing but when you're first getting started don't get caught up on understanding every detail of what every function does just focus on the input and what's returned so for example when we call the Len function on a string so if I print out Len of this string test if I run this then as we saw in a previous video this just returns an integer that is the number of characters in our string so we have no idea what the code that produces that result looks like but we do know that we passed in a string and that it returned this integer and we'll see why here in a bit why looking at functions in this way will help you become better when working with python because we can treat the return value just like the data type that it is and understanding this will allow you to chain together some functionality so we know our hello function returns a string so we can treat that executed function just like a string so if we remember back to our string Methods remember that we can uppercase a string with uper so really we can take this executed function and just chain uper onto the end of it so now if we run this now we can see that our executed function returned the string hello function and then we were able to use the string method upper on that returned value to uppercase the string um okay so now let's look at how we can pass arguments to our function and real quick I'm going to remove that uper method so to be able to pass arguments to our function we'll need to create some parameters here within our parentheses so let's say that we wanted to customize the greeting that our function returns so let's create a uh a parameter called greeting and now within our function we'll return a string where we use that greeting instead of our uh hello text that we had before so now I'll just pass this in with a DOT format so now before we run this we have to pass in that greeting argument when we execute our function if we don't then we'll get an error so actually let's go ahead and run this and see this error so we can see that when we ran that it says that hello Funk is missing one required positional argument greeting so let's pass in that greeting argument to our hello function and to do that we can just pass it in directly here when we call our function so I'm just going to pass in uh high as our string so now if we run this then we can see that when we passed in that string High into our function that it set that greeing variable equal to the string high and then returned the string High function now this greeding variable doesn't affect any variables outside of the function its scope is only local to theun function which is nice because we don't have to worry about it affecting anything we don't want it to affect so and if you want to learn more about python scope then I do have a detailed video going in depth as to how that works exactly and I'll leave a link to that video in the description section below okay so right now this greeting parameter is a required argument and that is because it doesn't have a default value now if we had a default value then it would just fall back to the default value whenever we didn't pass that argument in so let's see an example of this so let's say that we also want to be able to pass a name to our hello function and it'll return a greeting and the name so we can add that to our parameters by putting in a comma here and saying that we also want to accept this name parameter but let's say that if no name is passed in then we want to have a default value of U so we can just say name is equal to U and now let's add that to our return string so I'll put in a comma space and then another placeholder and we'll pass in that name so what this is going to do is it'll return a greeting and a name separated by a comma and a space so if we run this then we can see that even though we didn't pass in a value for the name argument when we executed this function it didn't throw an error and instead Ed the default value that we specified as U but if we want to pass in a value then it will use that value instead so when we execute this function if I was to say name is equal to and we'll say Corey and run that then now we

### Positional keyword arguments [10:12]

can see that printed out the greeting with the name that we passed in um now your required positional arguments have to come before your keyword arguments now if you try to create a function with those out of order then it's going to give you an error now this is a little more advanced topic that tripped a lot of people up but at some point you'll probably run across a function in Python uh that looks something like this so I'll say def student info and you might see something where you see this star args and star quars and so let me just go ahead and within this new function here I will print out args and I'll also print out quars so let's not really worry about this function name for now it's the arguments that I want to focus on so seeing this star args and star quars can seem confusing at first but basically all it's doing is allowing us to accept an arbitrary number of positional or keyword arguments so for example let's say that this student info function takes positional arguments that represent the classes that the student is taking plus the keyword arguments passed in will be random information about the student so you can see in both of those examples we don't know how many of these positional or keyword arguments there will be and that's why we use star args and star quars and the names don't have to be args and quars but that's a convention that you'll see a lot so it's always good to stick with convention so that people can understand your code so let's call this function with some random values so I'm going to say student info and first we want to pass in some positional arguments of the classes that they're taking so we'll say math and art and now for our keyword arguments we'll pass in some random information about the student so we'll say name is equal to John and age is equal to 22 so now if we run this then we can see that when we printed the args it's actually a tupal with all of our positional arguments and our quars are a dictionary with all of our keyword values so once you have that tupal and that dictionary then you'll be able to do whatever you want with that information now sometimes you might see a function call with arguments using the star or double star now when it's used in that context it will actually unpack a sequence or dictionary and pass those values into the function individually so to see what I mean let's make a list in a dictionary of everything that we just passed into our function and just to clear up some room here I'm going to go ahead and delete the hello function that we started off with so now I'm going to create a list called courses and I'm going to set this equal to math and art that we passed in before and instead of a tupal I'm going to make that a list so now for the student info I'm going to create a dictionary called info and set that equal to those values so now let me get rid of our positional and keyword arguments here so let's say that we wanted to pass all of these courses in as our positional arguments and the info dictionary as our keyword arguments so if we just pass these in as is and I passed in courses and info now if we run this then we can see that this might not be exactly what we thought instead of passing the values in individually and instead passed in the complete list and the complete dictionary as positional arguments so if we use the single star in front of our list and the double dictionary then it will actually unpack these values and pass them in individually so basically it will be the equivalent to our previous execution uh where we pass them in individually so to see what I mean let's add a star in front of this courses to unpack those values and a star in front of our dictionary to unpack those keyword values so now if we run this and we can see that we got what we had before um we can see that when our function prints args it's the values from our list that we unpacked and our quars is equal to the dictionary values that we unpacked now I know that's a little confusing especially to you know get the idea that whenever you're passing these in that it unpacks the values and within here it's for accepting an arbitrary number of positional or keyword values but uh it's a little more advanced of a topic and I know it's confusing but hopefully it makes some sense and you'll be able to better understand what's going on if you ever run into something like that okay so lastly I wanted to run

### Example [15:02]

through an example that ties together everything we've learned so far in this series of videos so I have some code here in my Snippets file that I'm going to grab real quick and paste into the file that we've been working with so now let me lower this output a little bit so that we can see everything here now these are actually a couple of functions that I grabbed in the python standard Library I modified them very slightly but it's basically the same and I wanted to show that even though we've only gone over the fundamentals we're already able to look at some code from within the standard Library itself and understand what's going on so at the top here we have a list called month days and this has the number of days in each month now the first index here is just a placeholder that's not going to get used um we're only going to be accessing indexes one through 12 since those are the months and then we have a function here called is Leap which determines if a year is a leap year it takes a single argument that is the year that it's checking and we can see that there's this string um after the function definition with three quotes and this is called a dock string and dock strings help document what a function or a class is supposed to do so it's a good practice anytime you write a function to write a doc string that goes along with it explaining what that function is supposed to do now this part here can seem a little intimidating but it's not important that you understand how a leap year is calculated there's not a lot of people who know that off the top of their head um but for various reasons this is how a leap year is calculated and it's not important but you could probably figure out what this uh conditional is doing so we're saying that if the year is divisible by four and uh it's not divisible by 100 or it's divisible by 400 so like I was saying there's a lot of different reasons why uh leap years are determined this way and if you don't know that that's completely fine but this function here is going to return true if a year is a leap year and false if it's a non-leap year and down here we have a days and month function that takes a year and a month as arguments and it'll return the number of days in that month so if we look at how this function works we can see that it first checks if a month is between one and 12 and if it's not then it returns that it's an invalid month and then it checks if the month that we're working with is the second month which would mean that it's February and is a leap year using our function up here at the top then it returns 29 if both of those are true and lastly if it makes it to the end without having returned anything yet then it will index into our month days and list up here at the top and return the value of our month so let's just run through this one time and see how these functions work so outside of both of the functions we're going to go ahead and first use this is Leap Year function so we'll say is Leap 2017 so if we run this then it returns false so we ran this function is Leap passed in 2017 as our value and it went through this complicated conditional here and determined that was false but if we type in 2020 here and run that then we can see that it returns true that 2020 is a leap year but now let's try our days and month function which is going to be a little bit longer of a walkthrough so we'll say days and month and we'll pass in a year so it takes a year first we'll pass in a year of 2017 and we'll pass in a month of two which is February now since 2017 is not a leap year then this second month which is February should only have 28 days so if we run this then we can see that we got 28 so let's walk through exactly what happened just so we're sure that we understand so we executed our days and month function with our arguments of 2017 for the year and two for the month so it comes in uh to our days and month function and it sets this year variable equal to 2017 and this month variable equal to two so let's comment those here just to keep track of them through our walkthr so I'll put a comment for year as 2017 and a comment for month as two so first it checks if our month is not

### Outro [19:32]

between 1 and 12 our month is two so it is in that range so it doesn't meet this conditional and since it doesn't meet that conditional then we just continue on so our next conditional asks if the month is equal to two and is a leap year so our month is equal to two but this is Leap function runs through its code with the year 200 17 and returns false so since is Leap is false and we're using an and operator then the whole conditional evaluates to false so we move on and lastly it accesses the month days list at this month index and remember that our month is equal to two so it's accessing the second index and if we look up here to our month day list and go to our second index so 0 one two then we can see that that's equal to 28 so it should be returning 28 here and finally when we printed out that result 28 is what we got as our result now I know that was kind of a long walkthrough but I thought it might be useful to see how these things actually work together and how do you go about determining what a function should return based on the arguments that you pass in okay so I think that is going to do it for this video I hope that now you have a clear understanding of how functions work how we return values and the different ways that we can pass arguments in the next video we'll be learning how to import modules and also learn about some of the useful modules that come in the standard library but if anyone has any questions about what we covered in this video then feel free to ask in the comment section below and I'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to Simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon and there's a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching
