Python | Find the factorial of a number using recursion

Factorial using recursion: In this tutorial, we will learn how to find the factorial of a given number using the recursion function in Python? By IncludeHelp Last updated : April 13, 2023

Factorial Using Recursion Program in Python

Given an integer number and we have to find the factorial of the number using recursion in Python.

Example:

Input: 
num = 3

Output: 
Factorial of 3 is: 6 
#3! = 3x2x1 = 6

Note: Factorial of 0 and 1 is 1

Python program to find the factorial of a number using Recursion

# Python code to find factorial using recursion

# recursion function definition
# it accepts a number and returns its factorial
def factorial(num):
    # if number is negative - print error
    if num < 0:
        print("Invalid number...")
    # if number is 0 or 1 - the factorial is 1        
    elif num == 0 or num == 1:
        return 1
    else:
        # calling function itself i.e. recursive
        return num * factorial(num - 1)

# main code
if __name__ == '__main__':        
    #input the number 
    x = int(input("Enter an integer number: "))
    print("Factorial of ", x, " is = ", factorial(x))

    x = int(input("Enter another integer number: "))
    print("Factorial of ", x, " is = ", factorial(x))

    x = int(input("Enter another integer number: "))
    print("Factorial of ", x, " is = ", factorial(x))

Output

Enter an integer number: 5  
Factorial of  5  is =  120  
Enter another integer number: 0
Factorial of  0  is =  1 
Enter another integer number: -3  
Invalid number...  
Factorial of  -3  is =  None

Python Basic Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.