# Practice Makes Perfect Factorial

#1

factorial

It works, but I'm hoping someone could help explain the logic. I basically followed the code academy prompts, and I got a "way to go!" but I don't understand the code, in particular the return x * factorial(x-1), where the code "calls itself"

``````Replace this line with your code.
def factorial(x):
if x == 1 or x == 0:
return 1
else:
return x * factorial(x-1)``````

Factorial Question
#2

Part of this exercise is meant to practice what we know in solving this problem. It does not suggest using code that we do not understand. We should be writing an iterative algorithm to complete the factorial problem.

What you have above is a recursive function, something we have not covered up to this point. Best advice would be to try solving the problem another way.

As you have observed, the above function does indeed call itself, `x` times.

``````# let x = 7

factorial(7)
factorial(6)
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)``````

Each of these calls have to wait on the completion of the later call, which sets up a stack of calls that will begin to return once the base case (x == 1) is reached. The wind down of the call stack competes the series of multiplications.

#3

Following are links to a couple of past discussions about recursion that may help clarify the concept ...

In addition, there are some off-track Codecademy courses on Python and other languages. The following course offers exercises that use Python to write recursive functions ...

Keep in mind that the off-track courses were contributed by Codecademy users several years ago, and may contain some bugs.

#4

Thank you very much!

#5

I think this did suggest using code I didn't understand, with the hopes that as I saw it work it would become clearer. THank you for your answer.

#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.