Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

How might I combine these two functions into one recursive function to have this outcome: 

factorial(6)

1! = 1

2! = 2

3! = 6

4! = 24

5! = 120

6! = 720

Look at the below code:

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 the execution of these two offers the right response, I simply need to make it to one recursive function.

1 Answer

0 votes
by (26.4k points)

Try the below code:

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

Interested to learn the concepts of Python in detail? Come and join the python course to gain more knowledge in Python

Watch this video tutorial on how to become a professional in python

Browse Categories

...