Python Program to Find Factorial Using Recursive Function

Recursion is the process of defining something in terms of itself. In this program we will find factorial of a given number using recursive function.

Definition of Factorial: In mathematics, the factorial of a positive integer number n, denoted by n!, is the product of all positive integers less than or equal to n.

Factorial Examples: 4! = 4*3*2*1 = 24, 0! = 1, 2! = 2*1 = 2, ... etc

Python Source Code: Factorial Using Recursion


# Program to find factorial using recursive function

# Recursive function definition
def factorial(n):
    if n==0:
        return 1
    else:
        return n * factorial(n-1)

# Reading number from user
number = int(input('Enter number: '))

# Displaying factorial
if(number< 0):
    print('Factorial does not exist!')
else:
    print('Factorial of %d is %d' %(number,factorial(number)))

Output

Run 1:
----------------
Enter number: 13
Factorial of 13 is 6227020800

Run 2:
----------------
Enter number: -9
Factorial does not exist!

Run 3:
----------------
Enter number: 0
Factorial of 0 is 1

One Line Function Definition


# Program to find factorial using recursive function

# Recursive function definition
def factorial(n):
    return 1 if n==0 else n* factorial(n-1)

# Reading number from user
number = int(input('Enter number: '))

# Displaying factorial
if(number< 0):
    print('Factorial does not exist!')
else:
    print('Factorial of %d is %d' %(number,factorial(number)))

Output

Enter number: 5
Factorial of 5 is 120