Factorial help


#1

hi this is mine it's not working so please help:

def factorial(X):
    for num in range(1,X):
        fac=num*X
    return fac

Factorial HELP
#2

because fac is created inside the loop and set to a certain value, you can see this:

def factorial(X):
    for num in range(1,X):
        fac=num*X
        print fac
    return fac
print fac(5)

see how each time, fac is just num*X? That is not working. You should set fac outside the for loop, and then add the multiplication to fac.


#3

Need help with below:
Oops, try again. factorial(3) returned 2 instead of 6

What is wrong here? (seems i lost indent while pasting)

def factorial(num):
    factnum = 0 
    while num > 1:
        factnum = num * (num-1)
        num = num-1 
        if num == 1:
            break
    else:
        factnum = 1
    return factnum

Here is indented code


#4

now each run of the loop, you just set a new value instead of updating factnum.

Wen declaring factnum, make it one. then in each run of the loop, update it:

factnum = factnum * num

this way, you update factnum, in your case, factnum simply get set to a new value each time. You can see this if you add print statements. which is why factnum(3) is 2, since the last run of the loop will be: factnum = 2 * (2 - 1)


#5

Thanks ,this resolved my issue.


#6