recursive factorial function

user531225 picture user531225 · Dec 21, 2010 · Viewed 72.6k times · Source

how can I combine these two functions in to one recursive function to have this result:

factorial(6)
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

these are the codes

def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       return n * factorial( n - 1 )  # recursive call
def fact(n):
       for i in range(1, n+1 ):
               print "%2d! = %d" % ( i, factorial( i ) )

fact(6)
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720

as you see execution of these two gives a correct answer, I just want to make it to one recursive function.

Answer

pythonFoo picture pythonFoo · Dec 21, 2010
def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       returnNumber = n * factorial( n - 1 )  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber