Factorial - can't print out my result?



My code is successful with no error messages, but I wanted to print out my 'result' variable at the end, as well as return it.

However adding the 'print result' line into my code (as shown) did not achieve this. Anyone know why not? Thanks.

P.S. I have also tried printing 'result' outside of the for loop, did not work.

x = raw_input("Please input a number: ")

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


You'll need to call the function for it to run


You can try the following:


Well in my own python 2.7 IDLE, calling the function afterwards seems to print out the result - but not in Codecademy.
Thanks anyway :confused:


You're probably doing something different that you're not aware of, all the more reason to figure out what it is.
Note that there is no part of the code you posted that invokes your function, much less prints a result.

Running it locally goes like this on my machine:

$ python2 er.py 
Please input a number: 5
$ # <- back at the prompt, program has terminated


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

x = raw_input("x")
x = int(x)
print factorial(x)


When you are printing the result. Try calling it after the print statement

Like: print factorial(x)

However, in your case since you are getting user input it is coming in as a string and not an int.

Try this: print (factorial(int(x))

That ensures that the value being pushed into the function is not a string and is able to be processed by the function.