5/15...What's wrong here?


#1
def factorial(x):
    if x == 1 or x == 0:
        return 1
    while x > 0:
        x *= (x - 1)
        return x

When running factorial(4), I get a result of 12, meaning the loop is stopping at 3. Can anybody tell me why? I've tried one less indent on the return line, but then I get an infinite loop. Tried a break with one less indent on the return and get 12 again. Tried a break with same indention and don't get past factorial(2). Somebody help me here.


#2

try this instead

def factorial(x):
    fact = 1
    while x > 0:
        fact *= (x)
        x-=1
    return fact

print (factorial(5))

You dont need the if block you had originally


#3

The correct answer is here:

def factorial(x):
if x == 1 or x == 0:
    return 1
else:
    return x * factorial(x - 1)

If you look up the hint, this is what is asked to do.


#4

import math
def factorial(x):
while x > 0:
x = str(int(x * x))
break
return x

print factorial(2015)

why is this code being rejected?


#5

Thank You!! :sweat_smile:


#6

how does "x * factorial(x-1)" loops itself down to one and times them all together? Could you explain?
Thanks.


#7

def factorial(x):
a=1
for s in range(x):
a=a*x
s=a
x=x-1
return s

this one worked for me well ... cool ,,

cheers guys..


#8

Honestly, all you needed to do was this:

def factorial(x):
    if x == 1 or x == 0:
        return 1
    else:
        return x * factorial(x - 1)

#9

This is how I did it (and it worked!)

def factorial(x):
    total = 1
    y = 1
    while y < x :
        total = total * (y + 1 )
        y += 1
    return total

#10

I hope it could be useful :smile:

def factorial(x):
while x > 2:
return x * factorial(x - 1)
if a == 2 or a == 1:
return a


#11

Because you are not being asked to use the factorial function.