# Factorial

#1

``````def factorial(x):

x += int(not-x)
while x == x:
return x
for i in x:

return x* i``````

what is wrong with my code here?

#2
1. I think you put a little too much space in between the defining statement and the code.

2. Your code could use some shortening. Use mine:

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

print factorial(12)

^^^ Correct code.

#3

look i wonna understand than to get a code please look i am really tryin to make my own great code just tell me what o do exactly and whats wrong with the assignement and these things like what is wrong with that code:

``````def factorial(x):
if x == 2:
return x - 2
return x*(x-1)``````

#4

Oh okay!

1. (Line 2) Don't do `x == 2`. The reason why I did `n < 2` is just to know what to do when n is less than 2. You return 1. The other code is for when `n >= 2`. In your code, the computer doesn't know what to do when x is 1 or 0.

2. `Unexpected indent on line 4`. It looks like that is part of the if statement. Put it inside the function but not the if statement.

3.(Line 3) `return 1 not x - 2.`

4.(Line 4) Put factorial in front of the parentheses

I think that is it.

#5

What if `x != 2`? Even if `x == 2`, your result yields a 0 as in your first return statement, 2 - 2 = 0.

Try using a conditional statement for special cases such as `factorial(0)` and another for the rest of the numbers. Also, if you just use `return x*(x-1)`, the code will only run once.
Eg.

``factorial(4) = 12 # 4 * 3``

which isn't correct. You can use recursion by doing `return x * factorial(-1)` instead. Recursion will keep on decreasing and storing x until it reaches the special case (AKA base case) and then it stops and multiplies all the x's it has stored.

``factorial(4) = 24 # 4 * 3 * 2 * 1``

You can also do it in loops as it is less costly compared to using recursion:

``````def factorial(x):
result = 1
for i in range(2, x + 1):
result *= i
return result``````

#6

thanks i really understand now
```def factorial(x): if x < 2: return 1 return x*factorial(x-1)``` but why when i change the intention of x in here in line 4 it gives an error

#7

No problem

#8

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