5. Factorial - Not sure what is wrong with my code


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096


"Oops, try again. factorial(1) returned None, did you remember to return the result?"


def factorial(x):
    if x == int and x > -0.1:
        y = x
        result = 1
        while y > 0 :
            result = result * y
            y = y - 1
            if y == 0:
                return result
                break
print factorial(5)


#2

x > -0.1

Why not just x >= 0? :slight_smile:


return result
break

return statement terminates execution of the function, so there is no need for break here :slight_smile:


The real problem is here:

if x == int and x > -0.1:

To check if the x is an integer you should use function isinstance:

isinstance(x, int)

#3

Thanks! I completely missed that I put "x ==" instead of "type(x) ==". Thanks for the tip about return terminating the function.


#4

You're very welcome :slight_smile:


#5

Here's another solution that worked for me ..

def factorial(x):
x = int(x)
y = x
while y -1 > 0:
y += -1
x *= y

return x

print factorial(5)


#6

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