Recursion in Python

Till now, if I wanted to repeat things I always used if, while and for loops as explained in my previous blogs. But that is not the only way to repeat things, another solution is to use recursion while programming in Python. With recursion you are dividing the problem in smaller problems that will be solved by repeating the function in itself. So what you are actually doing is dividing the big problem in smaller problems. This site has a beautiful explanation about how the dividing works in a really easy understanding way. The site uses Santa Claus and how the present will be delivered at the houses as example. So if you don’t fully understand what recursion is please check that explanation.

Okay, let’s bring it in practice in Python now. The function needs to keep recalling and repeating himself till an certain condition is met. That is the reason why a recursive function always consists of two parts: the base case and the recursive case. The base case is the condition that needs to be met to stop recurring. It is import to have that, otherwise you get an infinitive code.

Okay now I am going to explain it further on the basis of an example. First you need to define a function, the function that I defined is called lessons_recursive and the input of the function is leftovers. My base case says that the recursion has to stop if there are no leftovers left. That becomes my if and returns of the condition is met. As long as the condition isn’t met, I want to print that there are still leftovers and I want it to display the amount of leftovers. I use an else and print(“still leftovers”, leftover). After that it is important to make a statement to decrease the leftovers. It is very important to use that because otherwise your recursion becomes indefinite. At the end you have to give input for the leftovers and call the function. In a whole you get this result:

I can understand that you are wondering now what the advantage of the recursion is relative to for example an if or else loop. They actually both have a slightly different purpose. The purpose of a loop is just to repeat things till the condition is met. The purpose of a recursion is meant to break down a big task in smaller tasks. If you want to know more about the differences, you can read my next blog about it.

Hopefully you understand some more about using recursion in your Python file. If you still don’t fully understand it, is this video where Joe James brings recursion into practic with factorials. Thanks for reading my blog!

Plaats een reactie

Ontwerp een vergelijkbare site met WordPress.com
Aan de slag