This is a simple python script to print factorial of a number.
The factorial of a non-negative integer n, denoted by n! is the product of all positive integers less than or equal to n. For example:
5! = 5 * 4 * 3 * 2 * 1 = 120
The program asks the user to input the number and calculates using the above method. In this program we use a recursive function to calculate the factorial of a number. A recursive function is a self-calling function, which calls itself unless the condition is false. This is the easiest method to calculate factorial of number.
# Python program to find the factorial of a number using recursion # recursive function def factorial(n): if n == 1: return n else: return n * factorial(n-1) # Getting input from user num = int(input("Enter the number: ")) # check if the given number is a negative number 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", factorial(num))
Enter the number: 5 The factorial of 5 is 120 Enter the number: -5 Sorry, factorial does not exist for negative numbers Enter the number: 0 The factorial of 0 is 1