# Factorial

#1

``````I am trying to wrap my head around where I am going wrong...

def factorial(x):
if x == 1:
return 1
elif x == 0:
return 1
else:
count = x
while count >= 0:
answer = count * (x - 1)
count -= 1
if count == 0:

I am getting the error:
factorial(2) returned 1 instead of 2

When I change my code to this:

def factorial(x):
if x == 1:
return 1
elif x == 0:
return 1
else:
count = x
while count >= 0:
answer = x * (x - 1)
count -= 1

factorial(4) returned 12 instead of 24

Could someone please explain where I am going wrong and what to do to fix it?

Thanks``````

#2

the biggest problem is here:

``answer = count * (x - 1)``

you assign something to answer, which means each iteration of the loop `answer` gets re-assigned. Instead, you should define answer before the loop, give it a value of 1.

Then in the loop increase answer:

``answer = answer * ??``

#3

Hey stetim94,

Thanks for the advice, but i now get this:

``````def factorial(x):
if x == 1:
return 1
elif x == 0:
return 1
else:
count = x
while count >= 0:
count -= 1
if count == 0:

Oops, try again. factorial(2) returned 1 instead of 2

Could you link me a full correct solution so i can see if i understand it?

Thanks!

#4

this code:

``````        count = x
while count >= 0:
count -= 1
if count == 0:

can be so much more efficient. lets start by removing this line:

``count = x``

lets change the while condition, we want the loop to run while `x` is greater then zero:

``while x > 0:``

this way, we can just use `x`. Then we multiply answer by x (not x - 1) and store the result of this in `answer`

then we decrease `x` by one.

after the loop, return `x`

given the loop is now far more efficient in design, you can do this

#5

``````def factorial(x):
if x == 1:
return 1
elif x == 0:
return 1
else:
while x > 0:
x -= 1
if x == 0:

I did it! I think that the line with the answer on it was definitely confusing me

#6

but do you understand now?

I would do the following:

``````answer = 1
while x > 0:
x -= 1
this way, answer is returned after your loop has finished running, now you can remove your `if` and `elif` which check for x equals zero and x equals one, since they are now redundant.