Factorial Question


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096#


Why does the function on top not work for giving me the factorial but the bottom function does work?


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


#2

Hi @halkio,

The first version of the factorial function calls itself with the same value of n that was passed to it. Therefore, it never resolves the calculation. It is an example of an infinite recursion.

For each call to itself, the second version passes a value to itself that is one less than the value that it was given. For any non-negative value of n, the recursion eventually resolves to the base case, where n is 0. When that happens, each invocation of the function can return a value to the invocation that called it, until all the invocations have completed.


#3

Thank you for your response!
I think the confusing part for me is that instead of defining a function for factorial I can instead just use

print factorial(x)

and it will give me the same result

Edit:This lesson may just be trying to teach me to do it manually though?
Your response made a lot of sense though, and I do understand how to do it manually now!


#4

Yes, the lesson explains how to do it manually and then has the user implement that algorithm as a Python program.

Though the hint suggests a recursive solution, it does not provide details on how recursion works. See the following discussions, which present the concept of recursion in a little more depth, and therefore may be helpful ...


#5

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