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 recursively.

Factorial Using Recursion in Python


# 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 Code for Factorial Using Recursion in Python


# 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