5 factorial


#1

hey guys, can anybodyhelp me on this one?
this is my code, but i guess im on the wrong way ..
the error message im receiving is:

Traceback (most recent call last):
File "python", line 8, in
File "python", line 4, in factorial
File "python", line 6, in factorial
UnboundLocalError: local variable 'fac' referenced before assignment

def factorial(x):
    if x > 0:
        for n in range(x):
            fac = x * factorial(n)
            return fac
            print fac
                  
print factorial(4)


#2

I tried with range but couldn't think of how to specify it while multiplying. So, I did it reverse way using while loop as follows and added extra 'if' condition for 0 and 1:
factorial = x
while x >= 2:
factorial = factorial*(x-1)
x = x-1
return factorial

However I would also like to know the answer using range.


#3

I tried this with 'range'. The following code was successful:

def factorial(x):
    result = 1
    for i in range(1,x+1):
        result = result * i
    return result

#4

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