Recursion for Python Beginners with Recursive Function Examples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome I'm Dave today we will learn about recursion in Python and I'll provide links to all resources in the description below I've got Visual Studio code open and a folder over here in the file tree for lesson 10 we're going to not only learn about recursion today but also review a few Concepts we've covered in previous lessons and once again refactor our rock paper scissors game so recursion happens in Python when a function calls itself so that would be a recursive function so let's get started today by creating a file in the file tree and we'll name this file recursion dot Pi okay now I'm going to add a function here that will be a recursive function so I'll start with the def keyword I'm going to call this function add underscore one it's going to have one parameter and that will be a number so I'll just represent that with num so when we call it with the argument we pass in it will be a number and then inside the function I'm going to say if num is greater than or equal to the number nine then we're going to return so this will end the function when the return keyword starts here so it will not go any further in the function then we'll say num plus one but after that I want to create a new variable called total and have it be equal to num plus one so this will only be created if the number is less than nine and now I'm going to print the total and then after all of this again this only happens if the number is less than nine I'm going to once again return and I'm going to call the add1 function and pass in the total value so this is the recursive call to the function it calls itself here on line 9. and notice we're returning that and we're passing in the new Total so it will continue to call itself until it is greater than or equal to 9 essentially and that's when it will just return the number plus 1 here so now of course this is just the definition the file is not calling the function yet so we need to call the function to see how it works let's do that with add underscore one and let's pass in the number zero so I'll save the file with control s and I noticed it scrolled up on me so I'm going to add a couple of lines so now when I save it will not scroll up there we go and now drop here and choose run python file and notice we get the numbers one through nine and you may be thinking why didn't we get the number 10 because we passed in 9 to the function and that is when it went here but notice there is no print statement here inside the if so we're not printing the number 10. the only way we might be able to do that would be to return a value from our function here so we could say my new Total is equal to add 1 and pass in zero and then when the complete recursive calls are all finished then we will print my new Total and now here on line 15 is where the number 10 would be printed so let's run our code again we can see we now get the number 10 but just one through nine are printed here with line 9 and the number 10 is printed here at line 15. and this makes it important to note this return keyword because if we forget and leave that out with our recursive call everything will go ahead and continue but we will not get a value returned to my new Total so let's go ahead and save this and I'll show what happens we run the code again and now instead of the number 10 we get none because we were not returning this recursive call so we want to make sure we do that and by the way none is a special value in Python it's not true or false it's just none but let's go ahead and put the return keyword back in here so we can get a value out of our recursive function so now when I save and run the code we once again have the number 10. now it's worth noting that you could use a loop to achieve this same result and that would be a good practice exercise for you go ahead and try to create a loop instead of a recursive call and you could do that inside of a function that would have the same output that we have here however recursion is a mathematical concept and sometimes it's just necessary and overall I think it's important that you can recognize recursion as a beginner so if you are reading someone else's code and you see that the function calls itself you'll know that that is recursion now before we move on to refactor our rock paper scissors game one more time I want to create another file in the file tree and let's just call this file example dot Pi because I want to review a couple of things we have covered in the past to add a little more clarity here so we're going to talk about while loops and how they evaluate the true or false condition just a little so I'm going to set value here equal to to true and then after that I'm going to say while value and we can use double equal signs to say true but most of the time you will just see while value and it implies that while value is true or while value exists which is something we're going to talk about so now I'm going to print the value and then after this I'm going to set the value equal to false so this is what we would expect from this Loop it would print true one time and then the value is changed to false and then when it comes up here for the second iteration when it wants to go back through the loop it will see that value is now false and the loop will exit so let's save this and see if that's what we get for our output yes we get true one time here in the output now it's also worth noting that we could set value equal to zero and it would evaluate as false 0 is considered false so we run the code again and we get true one time and it also exits but note what I said before about value so I said it doesn't really just have to evaluate to true it can be saying while value exists and that is because we could set value equal to a string like y say our user says they want to play Rock Paper Scissors again and so that input is y for yes and then it still exists so this will evaluate the same as true so now if I run the code we're going to get why one time instead of true because this evaluated as true if we set this to zero or false here we wouldn't even get the one print line that we are right now I'm going to make this into a slightly larger example now so I'll say count equals zero and we'll still have our while value here and then let me start out with count plus equals one so instantly we'll increment the count variable by one so now it is equal to one the first time through the loop after that instead of print value let's print the count and then after that let's have an if statement I'll say if the count is equal to 5 then we're going to break out of the loop but then we can also have an else and inside the else I'm going to set the value equal to zero and then I'm going to use continue and I want to highlight this because I had a question about this and the question was when using the keyword continue is the loop still evaluated here at the top does it check the while value part and that answer is yes it's going to check the value every time to evaluate whether the loop should execute again or not so let's think about what this Loop does before we run the code and we're going to increment count by one and print the count so we'll have one as our output but so far it says if count equals five well it doesn't it equals one so we'll go down to the else and then here we're setting a value equal to zero now that's what we're evaluating here on line four does value exist or is it true and when it has zero it does exist but it's not true zero is equal to false so that should end the loop so the continue will just bring it back up here for the evaluation it will be evaluated and it will say no we're not going through the loop again so all we should get is a print count of one let's go ahead and run our code and see if that's what we get that is what we get just the one so what we're learning here is that yes using the continue keyword does cause an evaluation before the loop executes again now I've got the rock paper scissors code pulled up from our previous lessons and we've refactored it a couple of times I've created did a new file named rps3 dot pi as this would be the third time so if you've got that from a previous lesson bring it up if not you can get this code from the course resources so I'll leave that in there however I'm going to refactor it now so the starter code for this the last time we refactored I believe was lesson 8 which is also in the course resources the code in this lesson lesson 10 will be the refactored code so you'll find the finish code in lesson 10. okay now moving on we have learned several things that it could improve our game at this point so one of those things is functions so let's make our game a function and we're going to include everything after the Imports here at the top so we'll use the def keyword and let's call this play underscore RPS and then we have a colon so everything else needs to be indented to be part of the function so I'm going to start selecting here on line seven now scroll all the way down to the bottom except for this system exit here so I'll press the shift key and click and it highlights everything and then I'm going to tab in so now it should make all of that code part of the function so now everything is in the function except that system exit that we have right here and we'll probably end up moving it in the function too but we don't have to for now now let's go ahead and add the function call here at the bottom that we're going to need so it was play underscore RPS and we would need to call that of course to execute the function to see our Gameplay at all so we'll save that much and we now have a function for our rock paper scissors game now the next thing we can do is actually remove the while loop and we can use recursion in our function instead so let's let's do that by deleting the play again equals true and the while play again that starts the while loop but after we delete these now everything is indented too far underneath here it thinks it's part of the class RPS that we created up here so we need to select everything from line 14 once again scroll down to the bottom here and I'll click shift or press shift and click and then we're going to press shift and the Tab Key to tab reverse and go back out just a little bit so now everything is once again part of the function and it doesn't consider it part of our RPS class here that we start the function with either so just verify that your indentation is correct and python will read that correctly now we need to make some changes as you might have noticed I have a red squiggly line here where the continue keyword is that was applying to a loop but let's start at the top and work our way down one thing we still haven't fixed in our game is the player choice value if the input from a user was something that would cause an error as we cast to an integer here on line 16 we're not handling that at this point but we can do that so let's put an if statement underneath the input here where we get our player choice value and let's say if player choice and then we'll say not in and let's create a simple list because we know we're only expecting a one two or three and all user input is string so here we have not in one two or three in our list so we're making sure the player choice is one of those but if it's not let's execute some code in the if block here so we'll say print and now we're just going to take this message that we have in the system exit below because we will be removing this let's put this in you must enter a one two or three and after that this is a good time to use a recursive function call so we will return and we'll say play underscore RPS and that's all we need so we're calling the function here again and it will go back to the top and it will once again ask for the input of a one two or three and with that completed we can delete the other if statement we had here pre previously now note I've already pressed alt Z so visual studio code will wrap my code down I expected both of these lines to look like this first one however it's doing something a little weird here I've noticed when I delete this spacing and bring it back to look like the other one and then I save and auto formats it back this way so just note that if you see this in your code it is just happening automatically by Visual Studio code and I'm not entirely sure why but it's essentially all one line just like this line above is now let's scroll down and fix the area where we have the continue problem here but we're going to start here on line 41 where we have play again because remember we're no longer evaluating play again for the loop at the top I'm going to start though with a print statement and I'm going to print and here is where I'm going to ask the play again statement so I'll just copy that paste it in there and finish that print statement and then of course we can remove that same phrase from the print statement here but I want to have this input in a while loop and again this is correcting the input right now if we get a y for yes then it will play again and any other input not just a cube but any other input will quit the game but we want to limit the accurate choices to just Y and Q so here I'm just going to say while true so we're just looking for a True Value to begin the loop once again and then we'll have our play again I guess I don't need that extra line I could just tab this in so then we'll have play again ask for the input I'll get rid of one of these extra new line characters at the end though and now let's evaluate play again so we'll say if play again dot lower then not in and let's create another list and we'll just have y and Q as the two items in our list and then inside the block for the if statement I'll just use the continue keyword so if it's not y or Q it's just going to start the loop again and ask for y or Q so we're just asking our users to please specifically enter y or q and then our else will just issue the break statement so if they do enter a y or Q the loop stops now here the if statement below was checking for a y and we still want that so the loop is stopped they've entered a y and now this is a good place to put our recursive call to the function once again so play RPS because they want to play again if not we're going to still print the thank you for playing but we no longer have to evaluate play again for a loop so let's just take our system exit line right here here Ctrl X to cut it and Ctrl V to paste it over that line on 55 that was setting the play again value and now rock paper scissors should be ready to play and it is a recursive function so let's give it a shot and see if everything works as we expect it to so I'll enter one for rock and hey we won that's great do I want to play again yes let's play again let me enter something else like an a now that would have caused possibly an error before but now it just goes back and says we need to enter a one two or three how about a five nope one two or three so I'll enter two and now python wins so y for yes to quit or I mean to continue playing or Q to quit and let's enter a four instead no it just asks us the same question again so we're in that Loop until we get a y or a q we did y once already let's enter a Q and we quit so our game is we're working as expected you've now applied a recursive function to the rock paper scissors game remember to keep striving for Progress over Perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 13,435
Rating: undefined out of 5
Keywords: python, recursion, python recursion, recursion for python beginners, recursion in python, recursive, recursive functions, recursive functions in python, python for beginners, recursion for beginners, python tutorial, python tutorial for beginners, python recursion tutorial, python tutorial for recursion, python beginners tutorial, recursion in python beginners tutorial, recursion tutorial for python, how to apply recursion, recursive calls in python, recursive function call, py
Id: 72uVUU1boKo
Channel Id: undefined
Length: 17min 53sec (1073 seconds)
Published: Tue Apr 18 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.