Home » Python program to find Factorial of a given number

Python program to find Factorial of a given number

Python program to find Factorial of a given number

Hello people, welcome to Programming In Python! I am back to discuss how to find the factorial of a given number in Python.

Generally, a factorial on a given number is given by calculating its product with all the numbers below it.

Factorial is represented as `!`

For Example : 4! = 4 * 3 * 2 * 1 = 24

Master the basics of data analysis in Python. Expand your skillset by learning scientific computing with numpy.

Take the course on Introduction to Python on DataCamp here https://bit.ly/datacamp-intro-to-python

Program on GitHub

You can also watch the video on YouTube here.

Task :

To find the factorial of a given number.

Approach :

  • Read the input number for which the factorial is to be found using input() or raw_input().
  • Check whether the input number is negative and show an appropriate message
  • If the number entered is 0, print the factorial as 1
  • When the entered number is a positive integer and greater than 1, initialize a variable factorial as 1 then run a for loop from 1 to the number+1
  • Calculate the factorial as factorial * i
  • Print the result

Program on GitHub

Factorial – Code Visualization

Program :

num = int(input("Enter a number: "))
factorial = 1
if num < 0:
    print("Please enter a positive integer")
elif num == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1, num + 1):
        factorial *= i
    print("The factorial of", num, "is", factorial)

Output :

Factorial of a given number in Python
Factorial of a given number in Python

Ad:
The Complete Python Bootcamp From Zero to Hero in Python – Enroll Now.
Udemy

Program on GitHub

That is it for this post, hope you understood how to write a program to find the factorial of a number in Python. For more such math-related programs check this link.

Online Python Compiler

Leave a Reply

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