0

Using recursion in python 3 to get a factorial number

I have this little code in python 3 to get a factorial number: def factorial(n): if n == 0: return 1; else: return n * factorial(n - 1); I don't understand the last line... please can someone explain me what is going on?

24th May 2018, 9:37 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
4 Answers
+ 7
I think the explanation here is quite okay: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2465/ Basically, for 5 it would go like: f(5) = 5 * f(5-1) f(5-1) = (5-1) * f(5-1-1) f(5-1-1) = (5-1-1) * f(5-1-1-1) f(5-1-1-1) = (5-1-1-1) * f(5-1-1-1-1) f(5-1-1-1-1) = (5-1-1-1-1) * f(5-1-1-1-1-1) f(5-1-1-1-1-1) = f(0), so here we return 1 -- it's the so-called base case. Now, if you replace all f(x) with relevant input, you get 5*4*3*2*1*1 = 120, which is what f(5) is equal to.
24th May 2018, 9:48 PM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
0
there is a useful link for a youtube video there by the comments, have a look there.
24th May 2018, 10:49 PM
Lio K
Lio K - avatar
0
the last line is the actual recursion. keep calling the function factorial(n), reducing n by 1 in each call until n == 0 then stop and return 1
24th May 2018, 11:33 PM
E_E Mopho
E_E Mopho - avatar
0
thanks!
29th May 2018, 4:36 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar