How to Find the Factorial of a Number using factorial() in Python
In this tutorial, you'll learn how to find the factorial of a number using the factorial function in Python. In addition to factorial(), this tutorial also gives you sample programs to find the factorial of a number using recursion, the while loop and for loop statements without recursion.
Python factorial() Syntax
The syntax of the factorial() function is as follows:
math.factorial (number)
Argument
- number: The number that you want to find the factorial
Remarks
- To use the factorial() function, you need to import the math module.
- The number argument must be positive.
Factorial Examples
Example 1: Using the factorial() Function
The following is a sample program to find the factorial of 10 using factorial():
import math#find the factorial of a number using factorial()factorial_num = math.factorial(10)print("The factorial of 10 is ", factorial_num)
Result:
The factorial of 10 is 3628800
Example 2: Using the while Loop Statement
The following example illustrates a sample program to find the factorial of 10 using the while loop statement:
#find the factorial of a number using the while loop statementn = 10factorial_num = 1while(n > 0):factorial_num = factorial_num * nn = n-1print("The Factorial of 10 is ", factorial_num)
Result:
The Factorial of 10 is 3628800
As you can see, the above code is a simple program to find the factorial of a number using the while loop statement without using the built-in function factorial().
Example 3: Using Recursion
The following example illustrates a sample program to find the factorial of 6 using recursion:
#find the factorial of a number using recursiondef recursive_factorial(n):if n == 1:return nelse:return recursive_factorial(n - 1) * nfactorial_num = recursive_factorial(6)print("The factorial of 6 is ", factorial_num)
Result:
The factorial of 6 is 720
How to use the while loop statement in Python
Example 4: Using the for Loop Statement
The following example illustrates a sample program to find the factorial of 7 using the for loop statement:
#find the factorial of a number using the for loop statementn = 7factorial_num = 1for i in range(1, n + 1):factorial_num = factorial_num * iprint("The Factorial of 7 is ", factorial_num)
Result:
The Factorial of 7 is 5040
Here, we use the range function in the for loop statement. If you want to learn more about the range function and for loop statement, check out the following tutorials:
- How to use the range() function in Python
- How to use the for loop statement in Python
In this tutorial, you've learned how to find the factorial of a number using the factorial function in Python. Also, this tutorial provided sample programs to find the factorial of a number using recursion, the while loop statement, and the for loop statement without recursion.