Here are three ways to find the factorial of a number in Python.
- Using “for loop”
- Using “recursion”
- Using “math.factorial()” method
Method 1: Using for loop
You can use a “for loop” to iterate through number 1 till the designated number and keep multiplying at each step.
num = input("Enter a number: ") factorial = 1 if int(num) >= 1: for i in range(1, int(num)+1): factorial = factorial * i print("Factorial of ", num, " is : ", factorial)
Enter a number: 4 Factorial of 4 is : 24
Method 2: Using recursion
A recursive function is a function that calls itself during its execution. This enables the function to be repeated several times, as it can call itself during its execution.
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(4))
Factorial of 4 is: 24
Method 3: Using math.factorial() method
To calculate the factorial of a number in Python, you can use the built-in “math.factorial()” method.
num: It is an integer. If we provide float or any negative number, it will throw an error.
The “factorial()” method returns the factorial of the desired number.
# Taking input from user num = int(input("Enter the number to find factorial: ")) # Declaring one temporary variable to store the answer fact = 1 # Finding factorial of the given number for i in range(1, num+1): fact = fact*i print("Factorial of the given number ", num, " is: ", fact)
Enter the number to find factorial: 5 Factorial of the given number 5 is: 120
Example 2: If the given number is Negative
import math num = input("Enter a number: ") print("The factorial of ", num, " is : ") print(math.factorial(int(num)))
ValueError: factorial() not defined for negative values