5/15 Why won't this code work?

def factorial(x):
    if x == 0 or x == 1:
        fact = 1
        return fact
        for v in range(1, x+1):
            fact = 1
            fact = v * fact
            return fact

When I save and submit it says "Oops, try again. factorial(2) returned 1 instead of 2"


Think about when your return statement gets executed. Have you finished computing the result at that time?


Creo que el error está en el ciclo for, siempre que comienza el ciclo le dices que fact=1, deberías iniciar fact=1 antes de poner la orden for. Te dejo no obstante mi código que sí funciona para que le eches un vistazo. Aún no he aprendido a pegarlo de manera que se vean los espacios, lo siento.

x=int(input("introduce un numero:"))
def factorial(x):
if x==0 or x==1:
return fact
fact = 1
for i in range(1, x+1):
fact = i * fact
return fact
print (factorial(x))


I would assume not considering your response. I tried taking the return out of the for loop but it still didn't work. Then I tried using recursion but I don't really understand how that works. I'll keep trying in the meantime, but if you have any other suggestions that would be great.


Oh and I don't understand spanish


You're also setting fact to 1 every iteration, undoing what you had done to it before.


Oh wow I have no idea how I missed that, thank you


you need the return statement to be outside the for loop


def factorial(x):
if x == 0 or x ==1:
return 1
return x * factorial(x-1)
print factorial(4)

by recursion. as simple as possible !! KISS rule! :stuck_out_tongue:


The below holds true when x >= 1 it will return 1 for factorial(0) however but I have omitted an if else statement to cover this..

def factorial(x):
fac = 1
for n in range(1, x + 1):
fac = fac * n
return fac


Hello guys!

id be grateful to any comment on my code:

def factorial(x):
while x>=0:
return fac

i think the logic is ok... :confused:

edit: or maybe not considering negative ints is not correct?


Lets trace what happens when you call factorial(0) for example. You then get
0>=0 = True -> enter while-loop
fac = 1 * (0*(0-1) = 1 * 0 * (-1) = 0
x = 0 -2 = -2
-2>=0 = False -> exit while-loop
return 0


thank you for your reply, ill work on it


An easy method would be to import math.

import math

def factorial(x):
    if x == 1:
        return 1
    if x == 0:
        return 1
        return math.factorial(x)