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:
n! = n* (n-1) * (n-2) *........1
The factorial value of 4 is 24.
Output:
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:
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:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer