Factorial Program in Python

Factorial Program in Python

Home » Programming Language » Python » Factorial Program in Python
Factorial Program in Python
Factorial Program in Python

In this article of Factorial Program in Python we are going to write a python program to find the factorial of N number.

In programming there is lots of way to doing a simple or hard tasks or solving a problem, ways or you can say approaches aren’t limited in programming, but in this article the approaches or you can say we are going to use are mentioned below:

  • Factorial Program in Python using loop
  • Factorial Program in Python using recursive approach

As you know Python supports while and for loop so this program can be implement in both loops.

You’ll see the while and for loop example below of Factorial Program in Python

Factorial Program in Python using Loop

I already mentioned that python have while and for range loop so first we’re going to write our program to find factorial of n number in python using for range loop, you can also can it for in loop.

Factorial using for range loop

def factorial(n):
  print("user input is: {}\n".format(n))
  
  fac = 1
  for i in range(1, n + 1):
    fac = fac * i
    print("i = {}, {} * {} = {}".format(i, i, fac, fac))

  return fac


print("Factorial Program in Python")
# user input which will be passed to
# factorial function to get factorial
userInput = 7
fac = factorial(userInput)

print("\nFactorial of {} is {}".format(userInput, fac))

As you can see in this example we’re using for range loop and we’re starting from loop from 1 to n+1 so it won’t give us any wrong value, you can even run this to get factorial of 1 and two as well and it’ll work just fine.

If you run this code, you’ll get following output:

$ python main.py
Factorial Program in Python
user input is: 7

i = 1, 1 * 1 = 1
i = 2, 2 * 2 = 2
i = 3, 3 * 6 = 6
i = 4, 4 * 24 = 24
i = 5, 5 * 120 = 120
i = 6, 6 * 720 = 720
i = 7, 7 * 5040 = 5040

Factorial of 7 is 5040

Well this isn’t the smart way of doing factorial of a number why because what happens with your given digit is negative then what will happens let’s run this program again for negative value then you’ll see.

Factorial Program in Python
user input is: -7

Factorial of -7 is 1

As you can see our program didn’t broke but the loop is escaped, why because our loop meant to run on from range 1 to n+1 and we passed n as -7 which isn’t the right for range function of python.

Python range() function generates the immutable sequence of numbers starting from the given start integer to the stop integer. The range() is a built-in function that returns a range object that consists series of integer numbers, which we can iterate using a for loop.

So now you understand that our code isn’t completely bug free, below is the another example of code which is bug free.

def factorial(n):
  print("user input is: {}\n".format(n))

  fac = 1

  # check if the number is negative, positive or zero
  if n < 0:
    print("can't factorial of negative numbers")
    return 0
  elif n == 0:
    print("The factorial of 0 is 1")
    return 1
  else:
    for i in range(1, n + 1):
      fac = fac * i
      print("i = {}, {} * {} = {}".format(i, i, fac, fac))

  return fac


print("Factorial Program in Python")
# user input which will be passed to
# factorial function to get factorial
userInput = 7
fac = factorial(userInput)

print("\nFactorial of {} is {}".format(userInput, fac))

Now if you look at factorial function we’ve added conditions so we can handle that output and can print the statement for better(error handling) understanding.

You’ll see the output of this code for multiple inputs which is mentioned below:

For positive input:

$ python main.py
Factorial Program in Python
user input is: 7

i = 1, 1 * 1 = 1
i = 2, 2 * 2 = 2
i = 3, 3 * 6 = 6
i = 4, 4 * 24 = 24
i = 5, 5 * 120 = 120
i = 6, 6 * 720 = 720
i = 7, 7 * 5040 = 5040

Factorial of 7 is 5040

For negative input:

$ python main.py
Factorial Program in Python
user input is: -7

can’t factorial of negative numbers

Factorial of -7 is 0

For zero input:

$ python main.py
Factorial Program in Python
user input is: 0

The factorial of 0 is 1

Factorial of 0 is 1

Factorial using while loop

In this block we are going to use the same conditions and the way we’ve done before but the thing we’ll update is the loop, We are going to use while loop this time to find the factorial of n number.

Below is the example code to get the factorial of n number in python:

# Factorial Program in Python

def factorial(n):
  print("user input is: {}\n".format(n))

  fac = 1
  i = 1

  # check if the number is negative, positive or zero
  if n < 0:
    print("can't factorial of negative numbers")
    return 0
  elif n == 0:
    print("The factorial of 0 is 1")
    return 1
  else:
    while(i<=n):
      fac = fac * i
      print("i = {}, {} * {} = {}".format(i, i, fac, fac))
      i = i+1

  return fac



# user input which will be passed to
# factorial function to get factorial
userInput = 7
fac = factorial(userInput)

print("\nFactorial of {} is {}".format(userInput, fac))

If you look at the else condition we’ve update loop from for to while and added i<=n as well so whenever i becomes equal to n then immediately break the loop and return the result of factorial.

If you run the above code you’ll see the following output:

$ python main.py
user input is: 7

i = 1, 1 * 1 = 1
i = 2, 2 * 2 = 2
i = 3, 3 * 6 = 6
i = 4, 4 * 24 = 24
i = 5, 5 * 120 = 120
i = 6, 6 * 720 = 720
i = 7, 7 * 5040 = 5040

Factorial of 7 is 5040

I leave testing for negative and zero conditions on you try to run the code and comment your output in comment box.

Factorial Program in Python Using recursive function

Below is the code for how to recursively get factorial of n number in python:

# Factorial Program in Python


def factorial(n):
  # check if the number is negative, positive or zero
  if n < 0:
    print("can't factorial of negative numbers")
    return 0
  elif n == 0 or n == 1 :
    return 1
  else:
    # calling factorial function
    # so it can work recursivly
    return (n * factorial(n-1))



# user input which will be passed to
# factorial function to get factorial
userInput = 5
fac = factorial(userInput)

print("\nFactorial of {} is {}".format(userInput, fac))

In this code if look at we’ve added both condition we used in loop and also added on more within n==0, First we are checking if given value is negative or not if negative then return back and warn user about input, in next elif we’ve added condition so whenever n becomes 1 or 0 then return from that sequence and return the 1 as factorial of it, and in last we are calling our factorial function so it can process input until n become 1 or 0, 1 is going to come first in reverse sequence as we are using minus operator to subtract 1 each time from n so in end when n becomes 1 it’ll immediately return 1 and will start multiplying each value sequentially for final return value or answer.

To understand recursive approach you need to have good understanding of how function works recursively.

You’ll see the following output whenever you run the above code:

$ python main.py
Factorial of 5 is 120

I’ll update this article with more examples and approaches or variation so don’t forget to bookmark us. If you any user want to submit there example, variation, approach then please ping me.

kusingh@programmingeeksclub.com

your comments are appreciated and if you wants to see your articles on this platform then please shoot a mail at this address kusingh@programmingeeksclub.com

Thanks for reading 🙂

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.

Join Our Newsletter!

Join our newsletter to get our latest ebook "Ultimate JavaScript Cheat-Sheet", and Tips, Articles..

We don’t spam! Read our privacy policy for more info.

Leave a Comment

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


The reCAPTCHA verification period has expired. Please reload the page.