Recursion in Python3 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Recursion in Python3

Could please someone explain me how a recursion works? I've found an example: def tri_recursion(x): if x>0: result = x + tri_recursion(x-1) print (result) else: result=0 return result tri_recursion(6) I tested this code and modified it, but I don't understand HOW is the function calling itself (result = x + tri_recursion(x-1)???) Also, what is the role of the else statement? These are my 2 questions about recursion. The other lines of code seem ok to me. Thanks in advance!

5th Sep 2018, 11:59 AM
Virgil Baclanov
Virgil Baclanov - avatar
5 Answers
+ 1
Virgil Baclanov In the above code, the if statement is actually used to continue the loop rather than break it. By setting a condition that runs while the value of x is greater than 0, x will continue to decrease, being added to the expression as it goes along. Once the entire function has finished running, result should be the sum of: 6 + 5 + 4 + 3 + 2 + 1 + 0 (changing the value in the else statement will change the value of the last number).
5th Sep 2018, 4:43 PM
Faisal
Faisal - avatar
+ 3
When it comes to recursion, the main thing to remember is that you are always just running through the function again while the first run of the function is still not completed. It's equivalent to just calling a function several times over until a certain condition is matched with a value. An example of how this code would look when running: First: x = 6 Second: result = 6 + tri_recursion(5) Third: result = 6 + 5 + tri_recursion(4) .... ?: result = 6 + 5 + 4 + 3 + 2 + 1 The point of the else statement is basically just to break it out of the continuous loop of calling the function over and over again. In this case, once the value of x is less than or equal to 0 (remember that calling a recursive function with a value within that function being decreased will result in it to continuously decrease), then the loop will break.
5th Sep 2018, 12:47 PM
Faisal
Faisal - avatar
+ 2
Virgil Baclanov No problem! :ᴅ
5th Sep 2018, 10:48 PM
Faisal
Faisal - avatar
+ 1
Faisal pretty much understood, thanks, BUT isn't it the role of "if" statement in the example above to end the loop? I noticed that if i type "else: result=2", it won't print 6+5+4+...+1= 21, but 23 instead(adding 2 to the normal result)
5th Sep 2018, 1:14 PM
Virgil Baclanov
Virgil Baclanov - avatar
+ 1
Faisal YOU ARE GOLDEN! Thanks a lot!!
5th Sep 2018, 7:44 PM
Virgil Baclanov
Virgil Baclanov - avatar