Python Program to Find Factorial of a Number using Recursion, For, while Loop

Python programs to find factorial of a number; Through this tutorial, i am going to show you how to find factorial of given a number or user-inputted number in python using while loop, for loop and recursion function.

Find Factorial of a Number in Python

Here, i will write a python programs to find the factorial of a given number using for loop, while loop and without recursion and with recursion.

  • Python Program find factorial of a number 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 of a number using using While Loop

  • Get input a number from the user in program
  • Define fact variable and assign value it 1.
  • Iterate while loop to find factorial of given a number and store in it.
  • Print factorial of a number
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

  • Get input a number from the user in program
  • Define fact variable
  • Iterate for loop and calculate factorial of a number
  • Print the factorial of a number
#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

  • Define a function to calculate factorial of given number
  • Get input a number from the user in program
  • 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 Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *