Python Program to Find Factorial of Number Using Recursion
The factorial of a number is a mathematical operation that involves multiplying a given number by all of the positive integers that come before it, down to 1. It is denoted by an exclamation mark (!) after the number.
For example, the factorial of 5 is written as 5! and is calculated as follows: 5! = 5 x 4 x 3 x 2 x 1 = 120
Python Code :
The below Python program finds the factorial of a number using recursion:
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) # Prompt user for input n = int(input("Enter a non-negative integer: ")) # Check if input is valid if n < 0: print("Please enter a non-negative integer.") else: print("The factorial of", n, "is", factorial(n))
The factorial() function takes an integer n as input and recursively calculates the factorial of n. The base case is when n is equal to 0, in which case the function returns 1. Otherwise, it returns n times the factorial of n-1.
The user is prompted to enter a non-negative integer.
The input is checked to ensure it is a non-negative integer. If it is not, an error message is displayed.
If the input is valid, the factorial() function is called with n as the argument, and the result is displayed using the print() function.
Enter a non-negative integer: 5 The factorial of 5 is 120