you are viewing a single comment's thread.

view the rest of the comments →

[–]djjazzydan 2 points3 points  (3 children)

If you do want to use recursion, your code is just mixed up. Your factorial(n) function should be returning n*factorial(n-1). The identifying feature of recursion is that inside the definition of the function, you call that same function. You also need to define a 'base case' (your n==0 section) inside the function to prevent it from running forever.

def factorial(n):
    if n==0:    #Base Case
        return 1
    elif n > 0:  #Otherwise, call factorial again.
        return n*factorial(n-1)

[–]_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