---
description: Program to find the factorial of a number in Python with output and explanation. Factorial for negative numbers is not defined.
title: Python Program to Find the Factorial of a Number
image: https://www.guru99.com/images/python-program-to-find-factorial-of-a-number.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Factorial of a number in Python is the product of every positive integer up to that number. Python computes it with a for loop, an if-else check, recursion, or the built-in math.factorial() function.

- 🔘 **For loop:** Iterate from 1 to n, multiplying a running product to build the factorial.
- ☑️ **If-else check:** Guard against negative input, returning an error since factorials need non-negative integers.
- ✅ **Recursion:** A function calls itself with n-1 until it reaches the base case of 0.
- 🧪 **math.factorial():** Import math and call one built-in function for a fast, tested result.
- 🛠️ **Edge cases:** The factorial of 0 equals 1, and Python handles very large results natively.
- 🤖 **AI and data science:** Probability, combinatorics, and libraries like SciPy use factorials on arrays.

Read More

![Python Program to Find the Factorial of a Number]()

The sections below show four ways to compute a factorial in Python — a for loop, an if-else version, recursion, and math.factorial() — plus the underlying algorithm and applications.

## Factorial of a Number using for Loop

Let us take up the example of Python code that takes a positive integer as input to determine the factorial of positive integers. In the following code, the loop begins with one, and then it multiplies by each number that precedes the actual number whose factorial is to be determined.

The following Python code illustrates the factorial function using a loop.

**Python code:**

```
print ("Input a number")
factorialIP = int (input ())
ffactor23 = 1
for j in range (1, factorialIP+1):
   ffactor23 = ffactor23 * j
print ("The factorial of the number is “, ffactor23)

```

**Output:**

```
Input a number
4
The factorial of the number is 24

```

The above Python program takes the input of positive numbers only, and it does not have a check of negative numbers in it. In this program, the factor is 1 when j is equal to 1. When j is 2, the factor is multiplied with 2, and it will do the action till j comes at 4 to arrive at 24.

## Factorial of a Number using IF…else Statement

The following Python code illustrates the factorial function using a function. Unlike the loop version, this program also checks for negative numbers before computing the factorial.

In the previous Python code, the check for negative numbers was not applied, making the factorial function incomplete and prone to deliver an error message if negative numbers are given as an input.

In the given code, the loop begins with one and multiplies by each preceding number, and the function also validates the input for negative numbers.

**Python code:**

```
print("Enter a number for the purpose of determining factorial")
factorialIP = int(input())
def factorial(factorialIP):
   if factorialIP < 0:
     print ('Factorial does not exist')
     factor=0
     return factor
   elif factorialIP == 0:
     factor=1
     return factor
     print(factor)
   else:
     factor = 1
     for j in range (1, factorialIP+1):
       factor = factor * j
     return factor
  print ("The factorial of the number is ", factorial(factorialIP))

```

**Output:**

```
1) Enter a number to determine factorial
   -4
   Factorial does not exist
   The factorial of the number is 0

2) Enter a number to determine factorial
   4
   Factorial does not exist
   The factorial of the number is 24

```

This Python program accepts positive numbers and adds a check for negative numbers using the if and else statement, correctly returning 24 for an input of 4.

**Don't Miss:**

- [PyQt5 Tutorial with Examples: Create Python GUIs with Qt](https://www.guru99.com/pyqt-tutorial.html)
- [Python abs() Function: Absolute Value Examples](https://www.guru99.com/abs-in-python.html)
- [type() and isinstance() in Python with Examples](https://www.guru99.com/type-isinstance-python.html)
- [How to reverse a String in Python (5 Methods)](https://www.guru99.com/reverse-a-string-in-python.html)

## Factorial of a Number using Recursion

The following Python code illustrates the factorial function using recursion. In this example, a recursive function that takes a positive integer as input determines the factorial number.

**Python code:**

```
print("Enter a number for the purpose of determining factorial")
def factorial(num2):
  if num2 < 0:
    return 'Factorial does not exist'
  elif num2 == 0:
     return 1
  else:
     return num2 * factorial(num2-1)
number1 = int(input())
print("The factorial of the number is",factorial(number1))

```

**Output:**

```
Enter a number for the purpose of determining factorial
4
The factorial of the number is 24

```

The recursion can be explained as a concept wherein the function invoked in the Python module can call itself again and again. It runs until the Python condition present in the module is satisfied, wherein the function invoked is passed with a value.

In the above Python program, the function def factorial keeps calling itself recursively until and unless the number reaches zero. Once the number reaches zero, it initializes the number as 1, ending the recursion.

## Factorial of a Number using math.factorial()

The following Python code illustrates the factorial function using math.factorial(), which can be used by importing the math module.

This function does not accept negative integers, and it throws a value error when float numbers are provided.

**Python code:**

```
print("Enter a number for computing factorial")
import math
number1 = int(input())
print("The factorial is as computed comes out to be ")
print(math.factorial(number1))

```

**Output:**

```
Enter a number for computing factorial
4
The factorial, as computed, comes out to be 24

```

## Algorithm for the Factorial Program in Python

Let us take an example that illustrates the concept of factorial.

For determination of factorial 5, follow these steps:

```
5! = 5 x (5-1) x (5-2) x (5-3) x (5-4)
5! =120

```

Here, 5! is expressed as 120.

The following diagram helps in understanding the algorithm of computing factorial, and in this case, let us take an example of factorial 4!

[![Algorithm for the Factorial Program]()](https://www.guru99.com/images/python-factorial-example-1.png)

*Algorithm cum pictorial example of factorial 4!*

## Application of Factorial in Python

Factorial of a number has a wide level of applications in mathematics. Here are important applications of Python:

- Python helps in computation, followed with print factorial in faster and more efficient terms than other available programming languages.
- The Python code is easily understandable and can be replicated across different platforms, and the factorial Python program can be incorporated in several mathematical model-building assignments.

## FAQs

❓ What is the factorial of a number?

The factorial of a non-negative integer n, written n!, is the product of all positive integers from 1 to n. For example, 5! equals 5 × 4 × 3 × 2 × 1 = 120.

0️⃣ What is the factorial of 0 in Python?

By definition the factorial of 0 is 1. Every method — loop, recursion, or math.factorial() — returns 1 for input 0, and this base case also stops recursive calls.

🔢 Can Python calculate the factorial of very large numbers?

Yes. Python integers have unlimited precision, so math.factorial(100) returns a 158-digit result without overflow. Only memory and running time grow with the input size.

🔁 Which is better for factorial: a loop or recursion?

A [for loop](https://www.guru99.com/python-loops-while-for-break-continue-enumerate.html) is usually preferred. Both run in O(n) time, but the loop uses constant memory, while recursion adds a call stack that can hit Python’s recursion limit.

⏱️ What is the time complexity of a factorial program in Python?

Every standard method needs n−1 multiplications, so time complexity is O(n). The iterative loop keeps space at O(1), while recursion uses O(n) space for its call stack.

🛡️ How do you avoid a RecursionError for large factorials?

Deep recursion can exceed Python’s default limit near 1000 calls. Use an iterative for loop or math.factorial() for large inputs, or raise the ceiling with sys.setrecursionlimit().

🤖 Is the factorial function used in machine learning and data science?

Yes. Factorials appear in combinatorics and probability distributions like the Poisson and binomial that underpin many machine learning models. Data science libraries also offer vectorized factorial helpers for arrays.

🧠 Can GitHub Copilot generate a Python factorial function?

Yes. GitHub Copilot and similar AI assistants generate loop, recursive, and math.factorial() versions from a short prompt. Always review the suggestion for the negative-number guard and the 0! base case.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-program-to-find-factorial-of-a-number.png","url":"https://www.guru99.com/images/python-program-to-find-factorial-of-a-number.png","width":"700","height":"250","caption":"Python Program to Find Factorial of a Number","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/python-factorial-example.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/python-factorial-example.html","name":"Python Program to Find the Factorial of a Number"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/python-factorial-example.html#webpage","url":"https://www.guru99.com/python-factorial-example.html","name":"Python Program to Find the Factorial of a Number","dateModified":"2026-07-11T12:23:47+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-program-to-find-factorial-of-a-number.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/python-factorial-example.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/anna","name":"Anna Blake","description":"I'm Anna Blake, specializing in Python tutorials, offering clear and concise lessons to help you master Python programming efficiently.","url":"https://www.guru99.com/author/anna","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/anna-blake-author.png","url":"https://www.guru99.com/images/anna-blake-author.png","caption":"Anna Blake","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python Program to Find the Factorial of a Number","description":"Program to find the factorial of a number in Python with output and explanation. Factorial for negative numbers is not defined.","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/anna","name":"Anna Blake"},"dateModified":"2026-07-11T12:23:47+05:30","image":{"@id":"https://www.guru99.com/images/python-program-to-find-factorial-of-a-number.png"},"copyrightYear":"2026","name":"Python Program to Find the Factorial of a Number","subjectOf":[{"@type":"HowTo","name":"How to to Find the Factorial of a Number","description":"Let us take up the example of python code that takes a positive integer as input to determine the factorial of positive integers. In the following code, the loop begins with one, and then it multiplies by each number that precedes the actual number whose factorial is to be determined.The following python code illustrates the factorial function using a loop.","step":[{"@type":"HowToStep","name":"Step 1) How to find Factorial of a number using Function in Python Program","text":"The following python code illustrates the factorial function using function. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers.In previous python code, the check for negative numbers was not applied, making the factorial function incomplete and prone to deliver an error message if negative numbers are put as an input.In the given code, the loop begins with one, and then it multiplies by each number that precedes the actual number whose factorial is to be determined, and the function also checks for negative numbers.","url":"https://www.guru99.com/python-factorial-example.html#step1"},{"@type":"HowToStep","name":"Step 2) How to find Factorial using Recursion in Python Program","text":"The following python code illustrates the factorial function using recursion. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers. In this example, a recursive function determines the factorial number.The recursion can be explained as a concept wherein the function invoked in the python module can call itself again and again. It runs until the time the python condition present in the python module is satisfied, wherein the function invoked is passed with value.","url":"https://www.guru99.com/python-factorial-example.html#step2"},{"@type":"HowToStep","name":"Step 3) How to use math. factorial() in Python Program","text":"The following python code illustrates the factorial function using math.factorial(), which can be used by importing the math module.This function does not accept negative integers, and it throws an error message of value error when float numbers are provided. Let us take up the following python code that takes positive integers as input to determine the factorial of positive integers.","url":"https://www.guru99.com/python-factorial-example.html#step3"}]},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the factorial of a number?","acceptedAnswer":{"@type":"Answer","text":"The factorial of a non-negative integer n, written n!, is the product of all positive integers from 1 to n. For example, 5! equals 5 \u00d7 4 \u00d7 3 \u00d7 2 \u00d7 1 = 120."}},{"@type":"Question","name":"0\ufe0f\u20e3 What is the factorial of 0 in Python?","acceptedAnswer":{"@type":"Answer","text":"By definition the factorial of 0 is 1. Every method \u2014 loop, recursion, or math.factorial() \u2014 returns 1 for input 0, and this base case also stops recursive calls."}},{"@type":"Question","name":"Can Python calculate the factorial of very large numbers?","acceptedAnswer":{"@type":"Answer","text":"Yes. Python integers have unlimited precision, so math.factorial(100) returns a 158-digit result without overflow. Only memory and running time grow with the input size."}},{"@type":"Question","name":"Which is better for factorial: a loop or recursion?","acceptedAnswer":{"@type":"Answer","text":"A for loop is usually preferred. Both run in O(n) time, but the loop uses constant memory, while recursion adds a call stack that can hit Python\u2019s recursion limit."}},{"@type":"Question","name":"What is the time complexity of a factorial program in Python?","acceptedAnswer":{"@type":"Answer","text":"Every standard method needs n\u22121 multiplications, so time complexity is O(n). The iterative loop keeps space at O(1), while recursion uses O(n) space for its call stack."}},{"@type":"Question","name":"How do you avoid a RecursionError for large factorials?","acceptedAnswer":{"@type":"Answer","text":"Deep recursion can exceed Python\u2019s default limit near 1000 calls. Use an iterative for loop or math.factorial() for large inputs, or raise the ceiling with sys.setrecursionlimit()."}},{"@type":"Question","name":"Is the factorial function used in machine learning and data science?","acceptedAnswer":{"@type":"Answer","text":"Yes. Factorials appear in combinatorics and probability distributions like the Poisson and binomial that underpin many machine learning models. Data science libraries also offer vectorized factorial helpers for arrays."}},{"@type":"Question","name":"Can GitHub Copilot generate a Python factorial function?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot and similar AI assistants generate loop, recursive, and math.factorial() versions from a short prompt. Always review the suggestion for the negative-number guard and the 0! base case."}}]}],"@id":"https://www.guru99.com/python-factorial-example.html#schema-207332","isPartOf":{"@id":"https://www.guru99.com/python-factorial-example.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/python-factorial-example.html#webpage"}}]}
```
