Hi everyone, it's Graven for this sixth episode about Python language learning. In the fifth part, we saw how to create loops that allowed us to repeat the same instructions several times as long as a condition was fulfilled. Today, I propose to attack a brand new notion, which will deal with functions with this language.
So first of all, we are entitled to ask ourselves "What is a function? " Well it's just a sub-program that will contain a series of instructions, steps, things that will happen one after the other. If we take the case of a video game for example: we can find inside a function start (), to start the game; a teleport_players () function for teleport the players on a map, or else a function check_win () to detect the victory of this or that player and so on and so forth.
As you will have understood, the functions will have a fundamental role in our algorithms because each one tries to answer part of a problem, in order to obtain the expected result. Well. Now that we have seen the theory, let's move on to practice.
First of all, I will delete the code of the last video to start on new bases. Once done, we will be able to attack the development. The first step will be to create a function; but we will have to define before what she will do.
I propose to start with a function "welcome" that will send a console message welcome. So to define a function in python, we will first use the keyword "def"; like this. Then we will give a name to our function, so for example tell me a welcome function, I will call it "Welcome".
We try to call our functions Tiny with the conventions that I presented to you, that is to say that if for example the function is called "welcome message", we are not going to write "welcommemessage" like this or with a capital m at this level. Everything will be in tiny, but we will separate our different elements with an underscore. Like this.
So the dash of 8. Once you have defined the name of this function, we will open here small parentheses (I will explain later that we can pass information to inside these), and finally to open to start the block we will put here a:. From there, everything we put below, it's going to be instructions that will belong to this function welcome ().
So we could typically put a console message; just put the print function here and put the message in question in inverted commas. So for example I will put here "Welcome to my Youtube channel" like this. You can add as much instructions as you wish.
To add a second one, we will simply skip a line, and for example here I'm going to do a calculation, and in a third statement I will display the result of this calculation. So for example, here we will do a variable "result" which will be equal to 5 + 6, and below we will do here: print ("The result of the calculation) is "and, for example, here, we will put a comma to inject the value of the result. Great.
So we created our first function. Now if I run the script, it's not going to happen since we will have to call, trigger, our function. So to do that, you'll put yourself after the function, and put here welcome ().
So already, what we can note in relation to this first test is that if I call here the function "welcome", naturally, it will perform each of the instructions one after the other. Be careful though, if you call a function, before it will not work, since it will not find it. You really have to as a first step you create the function and later, further down the code, you call it (it does not work in the other direction).
It can also be noted that it is possible to call this function several times. Of course, if I call it three times, it will do three times this block of instructions. Look, if I run the script I have here a two and three times those instructions that were made.
So it works perfectly. Great. Of course if you have any questions, do not hesitate to ask them comment.
Well. Now that this is done we will attack another aspect of this notion. So either you delete the code that we just made at this level, Or you can right click on your project (my first project) and do here "new" -> "python file".
I will call it for example "year". like this. We do ok, and it will generate it.
Well. Now, inside this python file, I'd like us to start by creating a variable that will store the current year. To do this, we will create a variable that will be called "year" and that will be affect the value 2018.
Until then no difficulty, it is what we saw previously. Now, from this variable, I'm going to create a "next_year ()" function which will allow to move on to the next year. So to do that, we will define at the top a function that will be called "next_year ()", I'll open parentheses to pass information later.
Then we put our two points, we jump a line, and we'll start by putting a little message on the console just to say that it's the end of the current year, and we're going to here inject year that stores the current year. (so in our case 2018). Now that we said it was the end of the year, we will have to move on to the next year.
For that we will recover the value of "year", add a (so to go from 2018 to 2019,2 from 2030 to 2031 and so on), and we will have to reassign this value to the variable in question. You can of course simplify this operation by doing + = to 1, which is the same. Once we have moved on to the next year; we can very well here put a message by putting "beginning of the year", and here we will put the new value we have just calculated before.
However, as you will have noticed, these three instructions both have an error on the keyword "year". If we put our mouse on it, he tells us that he can not find the reference. Why ?
Since this variable is a variable overall. It belongs to our python script and not to the function in question. I could have done a variable here "year" which will be equal to 2018.
In our case it would have been a local variable. If I want to retrieve the global variable in question, I'm going to have to just here make the keyword "global" and put the name "year" simply. And that's it, the problem is solved.
So from now on, when I call my next_year () function, it will get that value, put "end of the year" (so in our case 2018); then we move on to the next year and we display that value. So I'm going to right click here -> run "year", not that it executes the other code, and there we can see that it is "end of the year 2018", "beginning of the year 2019". Then I'll do it again, I'll script, and look, "end of 2018," "early 2019" "end of the year 2019", "beginning of the year 2020".
So we can see that it works perfectly. What to simply remember is that: a global variable like this can be recovered in a function, provided to put here the small key word "global" and to specify the name, and there you can use it without problem, modify it and so on and so on . .
. So typically what we could note in addition to all that is a function also has the ability to return values, send results, that is to say we could very well do a function that does a series of operations, calculations, in the end it gets a result, and this result, instead of displaying it stupid console, we can very well use it everywhere in our code by calling the function in question (since it will send it back). So to show you how to do that, I suggest you change the file to split these different concepts.
So you're going to click on the project again -> new -> python file, and I'm going to call it this time computation, like this. so I propose you to do a function addition that will send the result of 5 + 5 to start. So here we will do a "def" -> "addition", we open the parentheses, two points, and here I'm going to make a variable result, which will store the result of my calculation, which will be 5 + 5.
Until then no difficulty, I can very well here make a print (result), and it will work perfectly. Only, as I told you, we can return a value, and for that I will use the little keyword "return", and put here my result. From now on, when I call the addition function, she does the instructions but she also sends me something, a result, which will be in our case 10.
(since I put it explicitly) So we're going to test that, but I'm going to print here by putting the result of the calculation, and here I will call on my function addition. So if I run the script, we have here "the result of the calculation is 10. " So what happened, I sent a message console, and at one point we called the function addition.
So it went inside, it did the calculation 5 + 5 that made the result 10, this was stored in my result variable and returned. So the addition returns the value 10 (so it's as if at that level I had 10 instead that was injected, quite simply). We could very well take a second example for a multiplication I'm going to do here a def "multiply", and here do result is equal to for example 5 x 8, and returned this result.
So here if now I call the function "multiply", and that I run the script, we can see that I have 40 as a result. So, of course, we do this in two stages but we could very well go straight to the point and directly returned the result of 5 x 8. Similarly for our addition, we could return the result of 5 + 5.
So obviously we can send something other than numbers; typically the message that I have here "the result of the calculation is" could be the source of a function return of a function that would be called for example "get_message" that I created just above. def get_message () and that would send me this message. Look, once again, if I run the script, I have this result.
Well. Now that this is done, I would like to create a second function which would be called, for example, addition2 and that would send me the result of 5 + 4 this time. How to do that?
And of course we would be tempted to copy and paste the code in question, to rename addition1 to addition2 (since otherwise we would have the same name and it would not work), and the result returned would be 5 + 4 this time. So here I'm going to copy the code in question, and here return addition2. So if I run the script, we can see that it works perfectly.
Now, I would like a third function addition3 which sends me this time 5 + 9. So the same, we will copy here the code in question and put here addition3, and send back 5 + 9. And the same, we will here make the result of the calculation and "Addition3".
If I run the script, we have here "the result of the calculation is 14" for this last calculation. So we can see that that works perfectly. But now, you're going to tell me ok Graven, it's all well and good, but if we have fifty calculations to make in our program, we will actually copy-paste this addition function 50 times, and add 1, 10, 20, 30, 50 and so on .
. . Well no, of course not.
It will be redundant, that is to say, it will be the same thing. And when in programming we have something that is repeated, we have a way to synthesize it. Look closely at these three functions.
Each time we do 5 plus a value 5 plus a value 5 plus a value . . .
So typically we could do a nth function that would be called "addition" and that would take this value that will change parenthesis and this is called a parameter. So this is a data that will be passed and we will be able to recover in our instructions. So I will call it for example "n" for number 2 points, here we will make the reference of our 5 plus, which will not change, and we will inject the variable value, the value that must change.
And so from now on, instead of calling addition 1 2 and 3, I'm just going to call addition, right there, and I'll put in parentheses the value that must change. So in the first addition, it was 5 then the second 4, and the third 9. So I pass arguments, data, in my addition function that I get right here and that I reinjecte at that level.
So I'm going to delete this and you're going see the result. Great. So now if I run the script, we have here the expected result.
So the only thing to remember is that when you call on a function, you are entitled to parenthesis of data, information, so-called arguments at that level, these arguments will then be retrieved here we will call parameters, these parameters will then be injected at the function level to make calculations, to do different things, different treatments. So be careful, when you create a function that necessarily requires a parameter at that level, you will be forced to give it when you call the function. If you do not put the argument here he will not find it and necessarily when you start the script you will have an error, it will tell you "the call of the addition function did not work" since you are missing an argument.
For try to solve this problem, either you put the value as shown, then you can put a default value here (for example we will put here 45). if now you start the script, look at the result. As you did not give any arguments during the first call of the addition function, it will have taken the default value 45 for n, and he will have made 5 + 45 so 50.
(It can be seen that the default value has been taken into account in the calculation). Great. We're done with this notion of parameters and arguments, now we will put it in a small practical case to see how it works.
So I will delete here the code in question, and we will create together a max function, which is going return the highest result among two values. So we will give it two input values, for example 45 and 12, he will tell us "45 is higher". We will give 500 and 1300, he will tell us "1300 is higher".
It will send us each time the highest value. So we'll do this together, but if you want to do it yourself to try put the video in pause and we are right after. So we jump a line, and we're gone.
We will start by defining a new function called "max" and which will require in parameter two elements: the value of a, and the value of b. From these two values, we will check to see if we should send back a or b. Here we make the two points, and it is here that we will begin our condition.
So if the value of a is greater than the value of b, it means that it is larger, so we will return that it is at the maximum value. Otherwise, we will send back b. If it's not one is the other.
So to test that, I'm going to create two small variables, one that's going to be called first_value and that will ask the user to enter in console the value of a, so the first one. Be careful, however, because this input () function that requires the user to enter a single console a value will return us text, while we we want an integer. So it's very important here to add an int, and to encompass everything to convert that into value as a number.
We go to the second value, second_value, and the same input "enter the value of b" and there, the second. Now that we have these two values, we simply need to create a max_value variable that will call the max function. And here we will give the first and the second value to this function, and after that we will have more than to display "the value max is ", and here we will put max_value here.
You can also skip this step, and directly do this if you wish. So let's go, we'll start the script, "enter the value of a", for example I'll put 45, "enter the value of b" 53, and there "the max value is 53". So it works perfectly.
Well. I now propose you to go to the third and last part of this video. We will deal with a concept that is relatively rare but that you may be required to use in certain specific cases.
This is the concept, attention, of recursion. So the name may seem very complicated, but it's simply because a function can call itself. I will give you a specific case, and you will understand better, and we can even create loops thanks to that.
So to do this I will create one last time a last python file that I will call last, for the sake of imagination. So typically, what I could do at this level would be to create an "add" function, which will take parameter a value, an integer, which I will call "a". This value, I'll be able to increment it by adding 1, so increment it's gone to the next value.
(so 1 to 2, 2 to 3 and so on. ) Then, I will display this new value, and to trigger this function as before we will add () giving a default value. So for example I'm going to put here 2.
So I'm going to right click on "last" -> run 'last'. So for now, what is happening is that it shows me 3. Why?
Since I pass 2 in argument here, I have the value 2. At this value 2 I add 1, so we go to 3, and this value 3 I display it in console. Thanks to the recursion, I will be able, at the end of the instructions, remember this add function by passing it the new value that has just been calculated.
Therefore, what will happen? We will add 2, so here we will have 2. We will add 1 so a will be equal to 3; we have a so we will have in the console 3; and recalling this function with the new value 3 will allow the process to be restarted, so it will close.
We will have here a = 3, so here we will go to 4 because we added 1. Then we put the value that was changed, so now 4 et cetera, et cetera. So I'm running the program, and there you look, it's going to loop, and I have plenty of values in my console.
(In my case it stopped because there is a limit for not that the program crashes. ). So that's really the principle of recursion.
We call the add function, it executes information; then she remembers herself with the new value that has been calculated. So, typically, what should be done is to add here a condition to verify that a is well below 10 to continue recursion. So here I made a tabulation to say that this element is inside this condition.
If I stay like this, Well, it will not work. Here. So if now I launch the script, we can see that it stops now at 10.
So it works perfectly. Well, here we go around this concept of function, obviously as at each end of video I suggest you do a little practical work to train you on everything we saw today. So the tp of today, it will be a function to calculate the number of vowels in a word (so that will be taken in parameter).
So first, you will need to define a get_vowels function _numbers (), which will take a parameter in parameter. (so it's a string) Then you will create a vowel counter, and for each letter of the word you check if it is a vowel. Of course, if it is, we add 1 to the counter, and at the end of the function you will send back the counter to know the number of vowels in this word.
You will have of course the answer of the tp in description, as well as a small quiz to train you on this new notion. So here is a little bit what I wanted to show you today, in any case I hope this video was pretty complete for you. If this is the case do not hesitate to put a like, to subscribe to the chain if it is not already done.
We exceeded 40,000 subscribers, so I wanted to thank you all one by one, it makes me very happy and shows that programming begins to be a subject that touches more and more people. Come on, it was Graven, hello to everyone, and see you next time.