Python programs to find factorial of number example; In this tutorial, you will learn how to find factorial of given number or user-inputted number in python using while loop, for loop and recursion fuction.
Factorial, in mathematics, the product of all positive integers less than or equal to a given positive integer and denoted by that integer and an exclamation point. Thus, factorial seven is written 7!, meaning 1 × 2 × 3 × 4 × 5 × 6 × 7. Factorial zero is defined as equal to 1.
Find the Factorial of a Number in Python
Let’s use the following algorithm to write a program to calculate/find the factorial of a number in python:
- Python Program find factorial using using While Loop
- Factorial of a number in python using for loop
- Factorial of a number in python using recursion
Python Program find factorial using using While Loop
Follow the below steps and write a python program to find factorial of a number using while loop
- Take input from the user
- Define fact variable
- Iterate while loop and find factorial of given number and store it
- Print factorial
num = int(input("enter a number: "))
fact = 1
i = 1
while i <= num:
fact = fact * i
i = i + 1
print ("Factorial of the number %d is %d" %(num, fact))
Output
enter a number: 5 Factorial of the number 5 is 120
Factorial of a number in python using for loop
Follow the below steps and write a python program to find factorial of a number using for loop
- Take input from the user
- Define fact variable
- Iterate for loop and calculate factorial of number
- Print the final result
#Python program to print factorial of a number
num = int(input("Enter the number: "))
fact = 1
#iterating through the num value
for i in range (1, num+1):
fact = fact*i
#printing the output
print ("Factorial of the number %d is %d" %(num, fact))
Output
Enter the number: 10 Factorial of the number 10 is 3628800
Factorial of a number in python using recursion
Follow the below steps and write a python program to find factorial of a number using recursion
- Define a function to calculate factorial of given number
- Take input from the user
- Use if else statement to check input number
- Call above define factorial function
- Print the final result
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = int(input("Enter the number: "))
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
Output
Enter the number: 6 The factorial of 6 is 720
Recommended Python Programs