Python

Writing the Factorial Program in Python

The factorial of a number is the number that you get after multiplying all numbers from 1 to that number. The factorial of a number is denoted by the ‘!’ symbol. For example, if we want to find out the factorial of 4, denoted 4!, then the result would be 1x2x3x4 = 24. There are many ways to find out the factorial of a number. The factorial can be determined in Python using the built-in function for loop and recursive functions. This tutorial shows how the factorial of a number can be determined using various functions of Python.

Example 1: Find the factorial of a number using the built-in function

Python has a built-in function named factorial() under the math module. The following script calculates the factorial of any number using a built-in factorial() function. In this script, any valid integer number will be taken as the input, and the function will calculate the factorial value of that number and print the factorial value of the input number.

#!/usr/bin/env python3
# Import math module
import math
# Take any number values
n = int(input("Enter any number: "))
# Find out the factorial
fact = math.factorial(n)
# Print the result of the factorial
print("The factorial of %d is %d" %(n,fact))

Output

After running the script, 3 is given as input number and the output of 3!, 6, is printed.

Example 2: Find the factorial of a number using the loop

The following script shows how you can calculate the factorial of any number without using any built-in function in Python. Here, the for loop is used to calculate the factorial of a number. Any input integer value will be taken and stored as the variable named n. A variable named fact is used to store the factorial result and is initialized to 1 before entering into the loop. If the value of n is more than one or equal to one, then the loop will iterate for 1 to n+1 times and will calculate the factorial value. Otherwise, the loop will check if the value of n is equal to 0 or negative. If the value of n is 0, then the factorial result will be 1; and if the value of n is a negative integer, then an error message will be printed.

#!/usr/bin/env python3
 
# Take a numeric value and store in n
n = int(input("Enter any number: "))
# Initialize the variable
fact = 1
# Find out the factorial if the input number is more than 0
if n >= 1:
   # Iterate the loop to multiple the numbers within 1 to n
   for i in range (1,n+1):
     fact = fact * i
   # Print the fcatorial result
   print("The factorial of %d is %d." %(n,fact))
else:
 if n == 0:
   # Print the result of 0!
   print("The factorial of ", n , " is ")
 else:
   # Print the error message
   print("You have to enter any positive number")

Output

The script is executed three times, according to the following screenshot. The script is executed for the input values 1, 6, and -8. The outputs are shown according to the input values.

Example 3: Find the factorial of a number using the recursive function

The function that calls itself during execution of the function is called the recursive function. The following script shows the way to calculate the factorial of any integer number using a recursive function. After taking the integer number as the input, the recursive function factorial_resursive() will be called, with the input value as an argument. If the input value is 0 or 1, then 1 will be returned. If the input value is negative, then the argument value will be returned. If the input value is more than 1, then the function will call itself by subtracting the argument by 1 again and again until it calculates the result of the factorial.

#!/usr/bin/env python3
# Take a numeric value
number = int(input("Enter any number: "))
# Define the recursive function to calculate the factorial
def factorial_recursive(n):
  # Store the factorial result of 0 and 1
  if n == 0 or n == 1:
    result = 1
  # Store the input number for negetive value
  elif n < 1:
    result = n
  # Find the factorial result in recursive way
  else:
    result = n*factorial_recursive(n-1)
  # Return the result
  return result
# Call the function
fact = factorial_recursive(number)
# Print the result for positive number
if fact >= 0:
  print("The factorial of %d is %d." %(number,fact))
else:
  # Print the message for negative number
  print("You have to enter any positive number")

Output

In the following screenshot, the script is executed three times with the values 1, -5, and 8.

Example 4: Find the factorial of a number with exception handling

The above three scripts only check whether the number is positive or negative. The following script calculates the factorial via a built-in factorial() function with exception handling. If the user gives any input without an integer value, then an exception will be generated, and an error message will be printed.

#!/usr/bin/env python3
# Import math module
import math
# Defie the try block
try:
 # Take a numeric value
 n = int(input("Enter any number: "))
 if n >= 0 :
   # Find out the factorial
   fact = math.factorial(n)
   # Print the result of the factorial
   print("The factorial of %d is %d" %(n,fact))
 else:
   # Raise exception if the number is negative
   raise Exception("You have to enter any positive number")
# print the error message for fractional input
except ValueError:
 print("You have to enter integer number")
# Print error message for negative input
except Exception as e:
  print('Error:%s' %e)

Output

The script is executed three times with the values h, -3, and 7 in the following screenshot. Here, the exception is generated for the value, ‘h.’

Conclusion

This tutorial shows some of the different ways you can calculate the factorial value of a number in Python. The concept of the factorial of a number and Python-based methods for calculating the factorial should be clear to the reader after reading this tutorial.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.