-2

Forgive me, I'm new, but I want to build a recursive function that takes a natural number and returns the product of all the natural numbers from 1 up to the given number. So factorial(5) should return 120 (5·4·3·2·1 = 120). However, I think I am just stuck. Here is what I have so far:

def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number

natural number -> natural number"""
   if x <= 0:
       return 1
   else:
       return x*(x-1)

Would the best route be to implement a counter?

holaprofesor
  • 271
  • 4
  • 15
  • You need to return the value like this `return x*(x-1)`. Also, `if x <= 0:` you should return `1`. Otherwise your answer will always be zero. – thefourtheye Mar 11 '15 at 03:21
  • 1
    see related question https://stackoverflow.com/questions/5136447/function-for-factorial-in-python – pigletfly Mar 11 '15 at 03:23

2 Answers2

1

First the statement in else needs to return a value, and because it's a factorial it should be x times the factorial of one less than x.

return x * factorial(x - 1)

The base case cannot be zero, firstly because the factorial of any number less than zero is undefined and any number times zero is zero, which makes the whole function pointless.

You should instead use the base case of:

if x <= 1:
    return 1

So your function is:

def factorial(x):
    if x <= 1:
        return 1
    else:
        return x * factorial(x - 1)
Will Richardson
  • 7,780
  • 7
  • 42
  • 56
0
 def factorial(x):
"""returns the product of all natural numbers from 1 up to the given number

natural number -> natural number"""
   if x <= 0:
       return 1
   else:
       return x*(factorial(x-1))

You also need to recursively call the function again.

hpatel826
  • 41
  • 5