Q:

Python | Find the factorial of a number using recursion

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now