Factorial


#1

I did some digging around in the Q & A forum and figured out how to do this exercise but there is a line of code that I'm not sure what it actually does. If somebody could explain it to me I would appreciate it.

Here is the line of code:

x = x * factorial(x-1)

if it helps here is the entire exercise. The indentations are present. The code works fine I just would like to know what that one line of code does (shown above ^^^^). Thank you guys.

def factorial(x):
if x > 0:
x = x * factorial(x-1)
elif x ==0:
return 1
return x

#3

Of course Python will have a problem with the code since it contains no blocks, and it should.

def factorial(x):
    if x > 0:
        x = x * factorial(x-1)
    elif x ==0:
        return 1
    return x

The above is known as a recursive function in that it makes repeated calls upon itself, each time with a diminishing argument. I'm not sure it is very efficient, but that is another story. Does it work? That is the question If not, then why?

Give this topic a read to see some of the variations on this function, both procedural and recursive. You should be able to gain some understanding from it. http://discuss.codecademy.com/t/5-factorial/16992/19


#4

What do you mean by blocks? I just wanted to know how line 3 works. By looking at that line of code Im thinking in order to find the value of x, it is multiplied by the ! of what ever x is minus 1. why is that line look so complicated for something as simple as 4! = 24


#5

def fn(x):
    #this is the function block
    while x > 0:
        # this is the while block
        if x % 2 == 0:
            # this is the if block

In Python, blocks have local scope. Variables in parent blocks can be accessed from a block, but variables in a block cannot be accessed outside of the block.

It looks complicated because in a sense it is. A proper recursion makes efficient use of the call stack. There is an example in the topic I pointed to earlier.