Python Functions

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
foreign in this video we're going to talk about functions in Python we're already familiar with a few functions we've used the print function throughout this entire Series so far and we've also used other functions like input but now we're going to get into a little more on what they are as well as how to make our own so let's start with the basics functions are code blocks that are only executed when they are called like all other code blocks where the code of a function starts and ends is controlled by indentation functions help keep our code organized and a lot of times much smaller this is because when you build and use functions properly it usually helps reduce the amount of repetitive code in your programs this is especially important for more generic functions that could be used to cross your entire program and functions aren't just useful for reducing repetitive code it also helps improve code readability let's say you have a pretty sizable block of code somewhere 30 lines 40 lines may be larger than that even if pieces of that block or even the whole block itself is not used anywhere else we could break it down into functions to make it easier to read this is incredibly important because when it is difficult to read code it is more difficult to debug issues when you find them and it is even more difficult for developers new to the code to understand what is going on so let's get into how to code a function so to create a function we need to start with a keyword and that keyword is Def d e f short for Define now we need to name our function and the rules for naming a function are pretty much the same as variables they can have letters they can have numbers and they can have underscores they have to start with an underscore or a letter they cannot start with numbers so we're just going to start simple not make anything too complicated so we're going to name this function say hello so say underscore hello once we have our name we now have to open a set of parentheses these parentheses actually have a purpose but I'll get into that a little bit later for now we're just going to leave them like this then we end this line with a colon and then we hit enter and as I mentioned before like with any other code Block in order for python to understand what code is going under the function and what code is not going in the function it's all determined on indentation level so now we're going to put our one line of code for this function not particularly exciting but I just wanted to keep this simple just to walk you through how to create a function so we're going to put print and say hello and then just backspace to go back to the main indentation level so now we're outside of the function because we're at the same level as the keyword Def so now we've defined our function now we need to call it because if we just run this file in Python like it is right now nothing's going to happen so we need to actually call the function so we can just simply say hello open close parentheses and we're good to go so now I'm going to open up our terminal and we're going to say python basic dot pi and it says hello parentheses are used to specify parameters parameters allow us to pass in data into these functions so that we can write code inside the functions to act on this data so to add a parameter we just name a variable so I'll put in name so that's our first parameter we don't have to really specify anything this is the only time where we can create a variable name and not actually assign it something this is just our way of saying hey when we pass something into this function it's going to be assigned to that name variable and because we have that parameter say hello now requires us to pass something into the function when we call it so if I try to run it you see we get an error because we didn't pass anything into the function it was expecting an argument to be put in so we're going to pass something in to say hello but first let's modify our print message so we're going to have it print out the variable name along with hello and then here I'm going to put in my name so now when we run it now says hello crowso and we can call this function as many times as we like and we can pass in different things in fact there's no real limitation at the moment of what I can put in here so I can pretty much put anything there's no checks inside this function to say hey I can't pass in a number so if I run this again it'll say hello crowso hello Beth and hello one two three four five now while we don't necessarily have to assign a value to name inside this parameter here we can give it a value and this is referred to as a default parameter value and how you do that is simply how you would assign any variable a value we type in equals and then give it a value in this case we're going to give it a string value of user so what this means is now we can call say hello without actually having to pass anything in because it now has a default value of user it won't yell at us for calling say hello without passing in a value see so if we don't pass anything in it'll say user in fact just uh I should probably have left that one in so say hello crowso when we pass in crowso but if we don't pass anything it says hello user there's no limit to how many parameters you can have inside your function so we can have multiple stuff you can say ID say ship you could say a whole bunch of things one important thing to note however if we do have parameters with default values those parameters must always be at the end you cannot have a parameter with the default value at the beginning of your list of parameters you cannot have it in between parameters that don't have default values it must be at the end and this is because parameters without default values are considered positional arguments and require you to pass in values for them so do you have to pass them in in the same order that those parameters are in so if ID is expecting a number and ship is expecting a string then when you call this function you have to pass in a number first and then you have to pass in a string and then if you needed to pass in a name you could pass in a name if you wanted to now as I said earlier parameters without default values are considered positional which means that parameters with default values are not positional they can technically be passed in any order as long as you specify them and what I mean by that is as long as I say ship equals cargo ID equals two three four five six and name equals prozo this is perfectly acceptable because we're specifying the actual parameter before we put in the value if we tried to do this without specifying the parameter's name if this function had input checking it would probably cause an error because we'd pass them in the wrong order because it would think that we were trying to pass the string cargo into ID when it was expecting a number for ID so before I run this let me add some lines in here to print everything else out so we'll say ID ship and then we'll also set that to blank so it just relies on the default values and then if I run this so it prints out the default values first and then it prints out the one where I passed in some values of my own so that's just one of many ways you can pass in variables um you can pass them in the same order and not specify the parameter names at all or if you want to specify the parameter names then you can do it like I did here so the reason you might want to do something like this is that maybe you have a function that takes in a whole bunch of arguments some of them are required but a lot of them have like default parameters and sometimes maybe you have to pass something into some of those default parameters but not necessarily all of them so you can specify them by name and that way the others will be left at the default value which means you won't have to basically pass in every single parameter every single time you only need to really pass in the ones you actually need which is why these are very useful now one other thing to talk about functions is the return value as you've seen from my previous videos when we call functions some of them return values back and in order to do that in our functions we have to use the keyword return Now by default all functions that do not specify a return value of their own will always return none so our function does technically return a value but it will return the none type so if we want it to return something different then we need to specify something so we're going to say return true just keep it nice and simple but if we wanted to keep track of that return value for whatever reason that we have to Now set the say hello function to assign its return value to a variable so that's what we're going to do here this is also a perfect opportunity to show you that since we're returning a Boolean value so so since it returns a Boolean value we can use this in a conditional statement right here like this and it will say if true then print out this message saying that we printed out the pilot info something simple and then of course let's print out X so that we can show that we returned the value true and can print it out so when we run it it prints out the default stuff and then it prints out true because it printed out X which was assigned the value by the say hello function and then the second time where we passed our own information we called it inside of an if statement and so it's check and see if the function will return true or false and since it returns true it printed out that little message that we put there and that's how you return data from functions which is very useful when you're using functions to calculate something and then you got to return that value and store it back from where it was called This is particularly useful for uh variables that are immutable which otherwise means they can't be modified directly so say you have an integer X and you passed it into a function and that function does some complicated math formula and then it Returns the value and then for some reason you want to return it back into X well you want to assign X to equal that function call that you're also passing X into same with strings and floats and stuff anything that's immutable where you wouldn't want to run something and you want to return a value for you to store it into back where you called it then that's how you would do that you would use a return statement and the cool thing about return statements is you can actually have more than one so let me show you what I mean by that let's do a simple input checking we're going to say if type ID is int print ID else return false so now we have two return statements if the ID ends up not being an integer it will return false so let's delete these two lines we'll copy this put a print statement in between so it's easier to see the two different entries and then we're going to set this to one two three and then we're going to run it and so for the first one because we passed in the correct info and we didn't put a string in the ID parameter it printed out just fine but in this one it only printed out the name because when it checked to see the ID it saw that it was in an integer so we returned false and then because it returned false the if statement that it called it did not print out this message so this is particularly useful because there are times where you're going to have functions that need to return different pieces of data depending on the situation that happened when it was executing so like if a function failed it may want to return false or return none if it succeeded it may want to return true or I may want to return the value that it succeeded on acquiring or calculating so that's typically useful to have so there you have it you can have multiple return statements inside a function as well which can be very useful depending on what it is you're trying to do another cool thing about return statements you can actually return multiple pieces of data at once and to do that you simply add a comma followed by whatever other piece of data you want to add in this case let's return the name and to keep things consistent we'll add a second value here too we'll say none now there are two ways to store the return data from a function when it's returning multiple pieces of data the first way is we use a single variable and we'll just use the default values for this and what will happen is these will be returned as a tuple so we'll store it into X as a tuple so if I I'm going to print out the type of X followed by X itself the other way we can do it is we can actually specify two variables to be assigned values by the function we're going to say status for the Boolean value and name for the name and then we're going to set it equal to say hello and then print out their types and their values as well so that's how you can do it so we're going to run this and as you can see here it returned it as a tuple and it printed out the Tuple here so we got true in user and for the second one it printed out the type for both status and name status is a Boolean name is a string and then it printed out their individual values so if you provide enough variables to store all the data it will store them individually if you only provide one then it will store it as a tuple okay now there's one thing I would like to talk about if you recall in my very first video getting started with python I mentioned entry points programs from certain languages like C plus plus and Java they require a specific entry point called the main function and you have to specify that in a file for the program to actually run when it's compiled in Python you don't really have that requirement the entry point is the file you feed into the python command but that doesn't mean we can't specify a main function and while it's not specifically required for you to define a main function in Python it's usually highly recommended to always Define a main function and it's simple just Define Main open close parentheses you can Define parameters if you want to you don't have to I rarely have to Define parameters in my own main functions but it depends from person to person and then you just start typing your code basically whatever code you would put in to start your program would go under the main function so print starting program hello friends ending program just something simple to keep things from getting too complicated so yeah basically imagine you're writing a whole program basically all of the code that would start your program would go under the main function and then you would call your main function down here simple as that so in the beginning of the video I mentioned that using functions can help reduce repetitive code and make things easier to read and so I have an example to show you how that would look so here I've got a file called No function example.pi basically it's just a whole block of code no functions being used so we got some variables to store our first middle and last name we've got a loop that will Loop through a menu give you choices so you can choose to enter in a first name a middle name and a last name and then we've got our input checking to check to see what choice we made and then we enter in the name based on the choice we made and then it'll check that name to make sure it's considered a valid name and in this case it's just making sure that the first letter is capitalized and that all characters in the name are letters so as you can see here for Twist one we input the first name we have a variable called invalid that will Mark as true if anything is detected to be invalid and then at the end of this it will check if invalid is true and if it is it will say oh that's wrong try again otherwise it will assign the input we provided into the variable first and it pretty much does that for all these choices it does the same thing for middle name and it does the same thing for last name pretty much the only thing different about these three choices is the variable name where you are using like we use l name for this m name for the second one an F name for the first one and maybe like the message is printed out other than that it's all the same it takes up 69 lines of code and while this particular block of code may not be considered unreadable we can pretend that it might be a little bit difficult to follow and read not all code blocks are going to be simple and straightforward and there could be a lot of stuff going on if you get a lot of confusing function names being called there could be a lot of confusing calculations being done so let's let's just pretend that this is kind of hard to follow now here's the program with functions so we've got a function here called check name and you may have noticed that looks very similar to what all these choices are doing except it's just acting on a parameter that we passed in called name and so it applies the name and everything is very generic it's not referring to anything it's first name middle name or last name it's just saying the name contains invalid characters and we've got our Boolean value invalid set the false and if it finds anything wrong it will set it to true and then it will return invalid at the end of the function call and our if statements that call the check name function we'll check to see if it was returned at true or false value and depending on which one it got it will act accordingly whether it's to print out the error message or to assign the name to its respective variable and as you can see these conditions are much smaller they're much more readable and the program overall is much shorter it's only 52 lines of code here that's because all this code is only written once whereas in here it's written three times so we have effectively reduced our code by 17 lines and while that may not be entirely impressive remember this is a small program in bigger programs it could be a much bigger issue and being able to reduce any number of lines of Code by however much is usually a good thing all right one last thing we're going to do and that is another exercise so you may recognize this script from our video on the input function this is the script we wrote where given a list of Pilots we could add new pilot to remove existing Pilots or just print out a specific Pilot's information in this exercise we're going to break this up into functions to make it simpler and easier to read so the first thing we're going to do is add our main function and to keep things a little simple I'm going to leave the pilot list on the outside you could still execute code and Define variables outside of it and it shouldn't be a problem so we're going to leave the pilot list on the outside because it'll make it easier to make it visible to all the functions so Define Main we're going to put everything under it and then we're going to Define another function show menu so this is where we're going to print out our menu and request for user input and here we're going to say return false we'll have it return a Boolean and we'll have it return a default Boolean return true and the reason we're going to have it return true or false is that we're going to have the while loop call the function show menu and while show menu returns true we'll just continue that way the while loop can continue to run until show menu returns false in which case it will exit the while loop and then eventually exit the main function which will end the program so that's why we have Choice return false when we enter q and otherwise we turn true so we now we have our first function but this is still pretty big and it's still pretty messy and it's still it's technically readable but we're going to pretend that it's not readable and that we can make this a little bit better so we're going to divide all of these choices into their own little functions as well so we're going to create another function called add pilot and then we're going to take the code that's in here and add it here and we're not going to return anything we're just going to leave it at this because pilot list is technically at the highest scope of this file so literally everything can see it so there's no point to return something to add it to the list it can directly modify the list most programs you probably wouldn't do this you would have variables within a specific scope so it can only be seen by certain things and therefore if you wanted to modify it you would have to do it by returning a value into it instead of modifying it directly but that really depends on what it is you're trying to do in this case we're leaving at the top so it's easy for all the functions to see it and just modify it directly so we're going to call the function add pilot now let's create another function remove pilot and now we have that and then finally print pilot info and there you have it we got our brand new text menu program it's much easier to read it's much more organized because everything is broken up into functions we've got our main function here which just has a while loop that continuously calls show menu and as long as show menu returns true it will just keep running once it returns false which will only happen when we press the q key to quit it will basically break out of the while loop and then break out of the main function because that's the end of the function and then the program will end and then our show menu it will basically print our menu options wait for us to put in the choice and then if we enter in one two or three it will act accordingly calling one of the functions which will perform the operation that we requested so we can either call add pilot call remove pilot and call Print pilot so the only thing left to do is that the bottom of our code call me so now we're going to run our program python text menu so it's running through the loop just fine it went to show menu function and it's printing out the menu for us to pick an option let's add a pilot prozo one two three four five six type frigate ship name eagle and now we're going to pick option two enter in a pilot ID one two three four five six and it doesn't print any feedback but it deleted the pilot with one two three four five six and then we hit three to print out pilot information one two three four five six and it prints out crowso and I can do that again two three four five six seven it's Beth three four five six seven eight and that's Aaron and then we hit Q to quit and that's all there is to it the program still works just fine it's just a lot easier to read and it's a lot more organized and that's it for python functions so I hope you've enjoyed this video and found it helpful and if you did then please hit the like button and leave a comment below to let me know what you think if you want to see more head on over to Wayfair coding Academy channel to check out my other content and while you're there subscribe to the channel to stay up to date on new stuff as it comes out thanks for watching and I'll see you all next time thank you
Info
Channel: Wayfare Coding Academy
Views: 8,328
Rating: undefined out of 5
Keywords:
Id: tiyh0lvJhCQ
Channel Id: undefined
Length: 25min 40sec (1540 seconds)
Published: Sat Jul 08 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.