The factorial of a number is the product of all the integers from 1 to that number. Mathematically, the formula for the factorial is as follows. If n is an integer greater than or equal to 1, then factorial of n is,
(n!) = 1*2*3*4....*n
Also, the factorial value of 0 is equal to 1 and the factorial values for negative integers are not defined.
Problem Definition
Create a Python Program to find the factorial of the user-provided number.
Factorial of a number using For Loop
num = int(input("Enter the Number :"))
fact = 1
if num < 0:
print("Factorial of negative number is not defined")
else:
for i in range(1,num+1):
fact *= i
print("Factorial of {} is {}".format(num, fact))
Output
Enter the Number :
7
Factorial of 7 is 5040
In this program first, we are taking input from the keyboard using the input()
function then we have a conditional statement for negative inputs since factorial of a negative number doesn't exist.
Then we have a for loop in range 1 to the number itself inside the loop we are simply iterating over loop variable i
and multiplying it with the fact
variable defined above. In the end, we are simply printing out the result using string formatting.
Factorial of a number using While Loop
The same program can be implemented using a while loop as follows,
num = int(input("Enter the Number :"))
fact = 1i = 1
if num < 0:
print("Factorial of negative number is not defined")
else:
while(i<=num):
fact *= i
i += 1
print("Factorial of {} is {}".format(num, fact))
Output
Enter the Number :6
Factorial of 6 is 720
Factorial function
You can wrap the above code in a function as follows,
def factorial(n): result = 1 for i in range(1, n + 1): result *= i return result # Example usage number = int(input("Enter a number: ")) print(f"The factorial of {number} is {factorial(number)}")
Factorial of a number using recursion
Alternatively, you can use recursion to calculate the factorial:
def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) # Example usage number = int(input("Enter a number: ")) print(f"The factorial of {number} is {factorial(number)}")
Factorial of a number using math module
Since Python always has a better way of doing things, it comes with a built-in solution for computing factorial of a number.
import math number = int(input("Enter a number: ")) factorial_result = math.factorial(number) print(f"The factorial of {number} is {factorial_result}")
Output
Enter the Number :5
Factorial of 5 is 120
The math
library which ships with Python has a factorial()
method that returns the factorial of the provided number.