# Factorial - is my formatting off?

#1

I found a code that works for this task, which seems way easier than what I came up with, but I still want to understand why my code isn't working. Is my formatting off? Did I introduce y in the wrong place? Am I asking to return the right value? Is my while loops actually looping at the right time?

The error I'm getting is: "Oops, try again. factorial(3) returned 3 instead of 6"
So I figure my mistake must not be too far out there..

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

#2

This should not be inside the loop. If you set y = 1, then set the loop,

``````while x > 1:
y *= x
x -= 1
return y``````

The lesson checker will not throw any curve balls and will only check with 0 or positive numbers so we don't need to refine the code to check for edge cases. Just keep it simple.

#3

Thank you mtf! That works. So I was mostly confused as to where to put the "return y".

#4

The only time we would write a return in a loop is if we want to exit immediately given a specific condition.

``if x % n == 0: return False``

as an example.

#5

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