Finding Factorial of a Number in Python Using Loops

Factorial of a non-negative number is defined as multiplication of all natural numbers smaller than it upto 1. For example – Factorial of -19 is not defined as its negative while factorial of 4 will be defined as 4 * 3 * 2 * 1 = 24. Quite simple just multiply n(n-1)(n-2)(n-3)(n-4)………..upto 1 and you would get factorial of number n.

In this article, I’ll discuss algorithm for Finding Factorial of a Number in Python using For Loop?

Python Program for Finding Factorial of Number

Using For Loop

  1. Ask user for some number num using input() function
  2. Use fact = 1 as a counter
  3. Iterate over range of numbers from 1 to num + 1 using For Loop, at each iteration multiply fact with current number
  4. After all of iterations from 1 to num + 1 using For Loop, the counter fact will become Factorial of Number num which was inputted by user at start of program
# Find Factorial of a Number in Python using For Loop

num = int(input("Enter a number: "))           # Ask User for some Input
fact = 1                                       # Use fact variable as counter
for i in range(1, num + 1):
	fact = fact * i
print("Factorial of ", num, " is =>", fact)

Output of Above Code

# If user inputted number num is 10
Factorial of 10 is => 3628800

Using While Loop

  1. Define Number whose Factorial need to be calculated as n = some_number
  2. Define a Python Function factorial(n) which iteratively multiply n with n-1, n-2 up to 1 and returns final number
  3. Firstly Python Function factorial(n) checks if n is less than 0, if so then return 0 otherwise checks if n is 0/1 if so then return 1
  4. Otherwise, if n is neither 0/1 or less than 0 then use fact = 1 as a counter and iteratively multiply it with n, n-1, n-2 up to 1 using Python’s While Loop. And then return fact, here fact will be Factorial of number n
# Python 3 program for finding Factorial using Recursion

n = 15       			 # Define Number whose Factorial to be calculated

def factorial(n):
	if n < 0:
		return 0
	elif n == 0 or n == 1:
		return 1
		fact = 1
		while(n > 1):
			fact *= n
			n -= 1
		return fact

print("Factorial of",n,"is =>",factorial(n))

Output of Above Code

Factorial of 15 is => 1307674368000

Leave a Comment