PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Programs to Find Factorial of a Number

Python Programs to Find Factorial of a Number

Updated on: March 31, 2025 | Leave a Comment

This article covers several ways to find the factorial of a number in Python with examples, ranging from traditional iterative techniques to more concise recursive implementations and the utilization of built-in library functions.

By understanding these different approaches, you can select the most efficient and suitable method for your specific needs, enhancing your problem-solving capabilities in Python.

Table of contents

  • What is Factorial
  • 1. Find Factorial of a Number in Python using for Loop
  • 2. Using Recursion
  • 3. Using Python’s Built-in math.factorial Function
  • 4. Using reduce from functools
  • Summary

What is Factorial

The factorial of a number is the product of all the positive integers from 1 to that number. The factorial of a non-negative integer ‘n’, denoted as n!.

To calculate a factorial, multiply the number by each previous integer until you reach 1.

  • The factorial formula is: n! = n * (n-1) * (n-2) * (n-3)…* 1
  • For example, the factorial of 3 is 3! = 3 * 2 * 1 = 6
  • The factorial of 0 is 1 (0!=1). 

You can also calculate a factorial by multiplying the number by the factorial of the previous number. For example, to calculate 6!, you can multiply 5! (120) by 6 to get 720. 

1. Find Factorial of a Number in Python using for Loop

Using a Loop (Iterative Method)

The for loop is an easy method to find the factorial of a number in Python. It involves multiplying numbers from 1 to the given number using a for loop.

Code Example

n = 5
if n < 0:
    print("Factorial not defined for negative numbers")

factorial = 1
for i in range(1, n + 1):
    factorial *= i     # Multiply factorial by loop counter

print(f'Factorial of {n} is : {factorial}')Code language: Python (python)

Output:

Factorial of 5 is : 120Code language: Python (python)

Explanation

  • Factorial is only defined for non-negative integers, so negative numbers return an error message.
  • Initialize factorial = 1.
  • Loop from 1 to n.
  • Multiply factorial by the current value of the loop counter i.

2. Using Recursion

Recursion involves calling the same function within itself to compute the factorial in Python. The function calls itself with a smaller value (n - 1), continuing until it reaches the base case. The recursive calls multiply n by the factorial of n-1.

How Recursion Works (Tracing factorial_recursive(3)):

Let’s manually trace the recursive calls:

  • factorial_recursive(3) = 3 × factorial_recursive(2)
  • factorial_recursive(2) = 2 × factorial_recursive(1)
  • factorial_recursive(1) = 1 (Base case)

Now, returning values:

  • factorial_recursive(2) = 2 × 1 = 2
  • factorial_recursive(3) = 3 × 2 = 6

Final output: 6

Code Example

def factorial_recursive(n):
    if n < 0:
        return "Factorial not defined for negative numbers"
    if n == 0 or n == 1:
        return 1
    return n * factorial_recursive(n - 1)

print(factorial_recursive(5))  # Output: 120Code language: Python (python)

Explanation

  • In the above example, factorial_recursive() is a recursive function that calls itself.
  • Error case: Factorial is only defined for non-negative integers, so negative numbers return an error message.
  • Base case: The factorial of 0 and 1 is always 1, so the function directly returns 1 in these cases.
  • Recursive case: Multiply n by factorial(n-1). Here, the function will recursively call itself by decreasing the value of the n, continuing until it reaches the base case.

3. Using Python’s Built-in math.factorial Function

math.factorial() is a built-in function in Python’s math module that returns the factorial of a given non-negative integer.

Code Example

import math

n = 5
if n < 0:
    print("Factorial not defined for negative numbers")
factorial = math.factorial(n)
print(f'Factorial of {n} is {factorial}')

# Output:
# Factorial of 5 is 120Code language: Python (python)

Explanation

  • We are using math.factorial(n) in Python to find the factorial of the given number. It is efficient and well-optimized.
  • n must be a non-negative integer (n ≥ 0).
  • Returns an integer value.
  • Raises a ValueError for negative numbers or non-integer inputs.

4. Using reduce from functools

In this approach, we use reduce() with lambda function to calculate the factorial of a number.
The reduce() function in Python (from functools module) applies a given function cumulatively to elements of an iterable, reducing it to a single value.

Syntax:

from functools import reduce
reduce(function, iterable)Code language: Python (python)

A lambda function in Python is an anonymous, single-expression function defined using the lambda keyword, often used for short, inline operations.

Syntax: lambda arguments: expression

For Example, result = reduce(lambda x, y: x * y, [1, 2, 3, 4])

In this example, we are applying the lambda function (x * y) to all values in the list [1, 2, 3, 4]. So, the output is 24 (1*2*3*4).

Code Example

from functools import reduce

n = 5
if n < 0:
    print("Factorial not defined for negative numbers")

factorial = reduce(lambda x, y: x * y, range(1, n + 1), 1)

print(f'Factorial of {n} is {factorial}')

# Output:
# Factorial of 5 is 120Code language: Python (python)

Explanation

  • Lambda Function:
    • The lambda function here (lambda x, y: x * y) takes two inputs:
      • x: Accumulator (stores the cumulative product).
      • y: Current number from the range.
    • It multiplies these two values and returns the product.
  • range(1, n + 1) generates numbers from 1 to n.
  • reduce() function applies a lambda function (x * y) to numbers in the range 1 to n.
  • The result of each multiplication is carried forward.
  • For Example, n = 5
    • Initial accumulator value: 1.
    • Multiply: 1 * 1 = 1 (first number in the range).
    • Multiply: 1 * 2 = 2.
    • Multiply: 2 * 3 = 6.
    • Multiply: 6 * 4 = 24.
    • Multiply: 24 * 5 = 120.
    • The result is 120.

Summary

These are different ways to find the factorial of a number in Python, showcasing diverse methods to achieve this. It begins by demonstrating the fundamental iterative approach, employing a for loop to accumulate the product of integers. Subsequently, it explores the elegant and concise recursive method, where the factorial of ‘n’ is defined in terms of the factorial of ‘n-1’.

Furthermore, the article highlights the use of the math.factorial() function from Python’s standard library, providing a readily available and optimized solution.

Article also discuss the use of lambda functions, reduce functions, or other advanced techniques.

By presenting these varied implementations, the article provides a comprehensive overview of factorial calculation in Python, enabling readers to choose the most appropriate technique based on factors like performance, readability, and the specific context of their application.

  • Use math.factorial() for the simplest and most optimized approach.
  • Use loops if built-in functions aren’t allowed.
  • Use recursion for learning purposes, but avoid it for large numbers.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement
Advertisement