# What am I doing wrong in factorial

#1

The error message is Oops, try again. factorial(3) returned 1 instead of 6. I don't know why it does this because for x =1 it should go to if x >=3 ... also, is there a quicker way to do this?

``````def factorial(x):
n = 0
while x >= 0 :

if x == 0:
return 1
x = x - 1
elif x >= 3 or n > 0 :

n += x * (x - 1)

x = x - 1
elif x == 1:
if n > 0:
x = x - 1
return n
else:
x = x -1
return 1

else:
if n == 0:
x = x -1
return 2
else:
x = x -1
return n``````

#2

That is a lot of code to chew through. Let's step back and review `factorial`...

1. Factorial 0 is 1.
2. Factorial is not negative.
3. n! = n * (n -1) * (n - 2) * .. * 1

Eg.

``7! = 7 * 6 * 5 * 4 * 3 * 2 * 1``

The first step is to exclude negative numbers...

``if n < 0: return "Input Error!"``

The next step is to initialize a return value that will be valid for both 0 and 1.

``````r = 1
# loop for n > 1
return r``````

#4

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