# 5.factorial with range()

#1

i try to use the commend range() o solve this problem but it didnt work.
can anyone expline me why i cant use it?
def factorial(x):
if x == 0 or x == 1:
return 1
else:
for i in range(1,x):
return x*i

#2

First of all in python it is pretty important that you format your code by the </> option or backs 3 backticks ` before and after your code otherwise the indentations will not be displayed and they are important as they are part of the syntax.

On the problem. Well what happens if you enter lets say factorial(3)? Well the if is false so you take the else path. There you start the loop and because of the return you leave the function with x*i which is in this case 3*1 which is not the expected 6.

The idea here is that the recursion makes use of the definition of factorial being x! = x* (x-1)!

Spoiler

So instead of that for loop. You only need to return x* factorial(x-1)

.
This is easy to write but not that easy to grasps so maybe take a pen and a piece of paper and go through it step by step.

#3

"for i in range(1,x):
return x*1"

well this doesn't help because somewhere in that range(), there will be a 0, and that will automatically make the multiplication problem 0.

this is my code and i hope it helps you:

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

``return result``