5/15 Why won't this code work?


#1
def factorial(x):
    if x == 0 or x == 1:
        fact = 1
        return fact
    else:
        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"


#2

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


#3

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:
fact=1
return fact
else:
fact = 1
for i in range(1, x+1):
fact = i * fact
return fact
print (factorial(x))


#4

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.


#5

Oh and I don't understand spanish


#6

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


#7

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


#8

you need the return statement to be outside the for loop


#9

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

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


#10

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


#11

Hello guys!

id be grateful to any comment on my code:

def factorial(x):
fac=1
while x>=0:
fac*=(x*(x-1))
x-=2
return fac

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

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


#12

Lets trace what happens when you call factorial(0) for example. You then get
fac=1
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


#13

thank you for your reply, ill work on it


#14

An easy method would be to import math.

import math

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