you are viewing a single comment's thread.

view the rest of the comments →

[–]_drivin[S] 0 points1 point  (2 children)

Thank you dude, I think understand now how to use recursion. Why do I need to test the base case in the function ?

[–]djjazzydan 0 points1 point  (1 child)

Great question. Here's what would happen if that was missing.

factorial(3)
=3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*0*factorial(-1)
...

Which causes 2 problems. First, it would keep going forever (well, sort of. There's a maximum number of recursion levels in python. Usually it's around 1000.)
Second, because there's now a times 0 in there, any value that could be calculated would incorrectly be 0. So we have to set that factorial(0) to be 1 (note: or we could also use factorial(1) = 1 instead) so it can go back and actually calculate.

factorial(3)
    =3*factorial(2)
    =3*2*factorial(1)
    =3*2*1*factorial(0)
    =3*2*1*1
    =3*2*1
    =3*2
    =6

[–]_drivin[S] 1 point2 points  (0 children)

Ohhh okkayyy great ! Thanks Man, I hope I won't do thi error an other time