5.Factorial help me out of this..?!



x=int(input("enter a number"))
def factorial(x):
    if x==0 or x==1:
        return 1
        return  (x*(factorial(x-1)))


Hello @dataace98389,

You aren't calling your factorial function, you have just defined it. So in order for a function to print to the console, you have to call

print factorial(x)


Hi, @dataace98389 ,

You have this ...

x=int(input("enter a number"))

While that line was not the source of the problem, which has already been correctly identified by @bartholomewallen, you should nearly always use raw_input rather than input to get input from the user when using Python 2.x. For Python 3.x, use input.

When input is used in Python 2.x, the interpreter will attempt to evaluate whatever the user enters, as code. This will not always cause a problem, but it could.

Try the following with Python 2.x ...

ans = input('What code would compute the length of "Monty"? ')
print 'You entered %s.' % (ans)

Console window session ...

What code would compute the length of "Monty"?  len("Monty")
You entered 5.

Notice that the user entered this ...


... but the output was this ...

You entered 5.

The Python interpreter actually called the len function, with "Monty" as an argument.


This is what I did:

def factorial(x):
    result = 1
    factors = range(1,x + 1)
    for n in factors:
        result *= n
    print result        # Not needed; for testing along with lines 9 and 10
    return result

    arg = raw_input("Enter a number:")

EDIT: Shortened this to:

def factorial(x):
    return reduce(lambda x, y: x * y, xrange(1, x + 1))


Without this I wouldn't have been able to complete it myself.