Python Program to Find the Factorial of a Number
What is factorial?
Factorial is a non-negative integer. It is the product of all positive integers less than or equal to that number you ask for factorial. It is denoted by an exclamation sign (!).
Example:
The factorial value of 4 is 24
Example -
Output:
Enter a number: 10 The factorial of 10 is 3628800
Explanation -
In the above example, we have declared a num variable that takes an integer as an input from the user. We declared a variable factorial and assigned 1. Then, we checked if the user enters the number less than one, then it returns the factorial does not exist for a negative number. If it returns false, then we check num is equal to zero, it returns false the control transfers to the else statement and prints the factorial of a given number.
Using Recursion
Python recursion is a method which calls itself. Let's understand the following example.
Example -
Output:
Factorial of 5 is 120
Explanation -
In the above code, we have used the recursion to find the factorial of a given number. We have defined the fact(num) function, which returns one if the entered value is 1 or 0 otherwise until we get the factorial of a given number.
Using built-in function
We will use the math module, which provides the built-in factorial() method. Let's understand the following example.
Example -
Output:
Enter the number: 6 Factorial of 6 is 720
We have imported the math module that has factorial() function. It takes an integer number to calculate the factorial. We don't need to use logic.