Python program find factorial of a number using recursion

Python program find factorial of a number using recursion

In this tutorial, we will discuss Python program find factorial of a number using recursion.

Factorial is a product of all positive descending integer begins with a specified number (n) and calculates up to one

Factorial of n is

 

  • Factorial is not defined for negative numbers
  • Factorial of zero(0) is: 1
  • Factorial of positive number is  given below

Example

factorial of 5 is

5!=5*4*3*2*1=120

factorial of 7 is

7!=7*6*5*4*3*2*1=5040

 

The factorial of a positive number n is given below

factorial of n is

n!=n*(n-1)*....2*1

 

In my previous post, I have explained the various ways to Find factorial of a number in Python

However, in this program, we embed the logic of the factorial program in the recursive function

The user can provide numbers as they wish and get the factorial according to their input

Program 1

def recursion_fact(num)://function definition
    if num==1:
       return num
    else:
       return num*recursion_fact(num-1)

#take input from the user

number=int(input("Enter the number for find factorial"))

#test the number is negative

if number<0:
        print("The factorial does not available for negative number")

#test the number is zero
elif number==0:
        print("The factorial of zero is 1")

#if the number is positive,  displays the factorial
else:
      print("factorial of" , number,"is: ",recursion_fact(number))

When the above code executed, it produces the following results

case 1

Enter the number for find factorial5
factorial of 5 is: 120

 

case 2

Enter the number for find factorial: 0
The factorial of zero is 1

 

case 3

Enter the number for find factorial: -6
The factorial does not available for negative number

 

Check out these related examples

Java code to find the factorial of a number

Java code to find the factorial of a number using Java method

Find factorial of a number in C

Find factorial of a number in CPP

Find factorial of a number in Python

Find factorial of a number using while loop

 

Suggested for you

Recursive function in Python

Python if.. else statements

Python function

Python recursion

Find Factorial:Python program to using function
Cpp program to check a number is even or odd using function
function in PythonPython languagepython program