Write a program to Find Factorial of Number Using Recursion in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Python program to find the factorial of a number using recursion def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n == 1: return n else: return n*recur_factorial(n-1) #to take input from the user num = int(input("Enter a number: ")) # check is the number is negative if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of",num,"is",recur_factorial(num)) |
This Python program uses a recursive function “recur_factorial()” to find the factorial of a given number “n”. The function takes an input argument “n” and checks if it is equal to 1. If it is, the function returns the value of “n” which represents the factorial of 1. If “n” is greater than 1, the function returns the value of “n” multiplied by the factorial of “n-1” which is calculated by calling the function recursively.
The program also takes input from the user in the form of an integer using the “input()” function and assigns it to the variable “num”. If the input number is less than 0, the program prints “Sorry, factorial does not exist for negative numbers”. If the input number is 0, the program prints “The factorial of 0 is 1”. If the input number is greater than 0, the program calls the “recur_factorial()” function with the input number as the argument and prints “The factorial of”, followed by the input number, “is”, followed by the value returned by the function.
Example output: