Home » Python » Python programs

Python | Find the factorial of a number using recursion

Factorial in Python: Here, we are going to learn how to find the factorial of a give number using the recursion in Python?
Submitted by IncludeHelp, on August 09, 2019

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 code to find factorial 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.