Factorial 5/15 Trouble


#1



Factorial 5


I keep getting this error message: Oops, try again. factorial(1) returned 0 instead of 1


The code technically works perfectly, as it returns exactly what I want it to. But for some reason, I keep getting this message. Why?

Thank you for your help!

def factorial(x):
    total = 1
    total = x * (x - 1)
    x -= 1
    for loops in range(x - 2):
        total = (x - 1) * total
        x -= 1
    return total
print factorial(4)


#2
def factorial(n):
    if n < 2: return 1
    return n * factorial(n-1)

You won't need the for loop! :smiley:


#3

Thanks! I figured out the problem, but through my own, really unnecessarily complicated way haha.

For anyone curious:

def factorial(x):
if x >1:
total = 1
total = x * (x - 1)
x -= 1
for loops in range(x - 2):
total = (x - 1) * total
x -= 1
else:
total = 1
return total
print factorial(1)


#4

Haha! But in the future you might want to use the easier, shortcut way. There is no need for longer code when you can shorten it a bit! :wink:


#5

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


#6

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

print factorial(3)


#7

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