Python Program to Find Factorial with Code and Output

By Btech Faqa

Published On:

Python program to find factorial with code and output

Join WhatsApp

Join Now

A Python program to find factorial is one of the most common programming questions for beginners, B.Tech students, and Python practical exams. It helps you understand loops, conditional statements, functions, recursion, and mathematical operations.

In this tutorial, you will learn how to write a Python program to find the factorial of a number using different methods. Each program includes simple source code, output, and a step-by-step explanation.

Whether you are preparing for a Python lab exam, practicing coding questions, or learning programming from scratch, these examples will help you understand factorial calculations.

What Is Factorial in Python?

The factorial of a non-negative integer is the product of all positive integers from 1 up to that number.

The factorial of a number nn is represented as n!n!.

For example:

  • 0!=10! = 1
  • 1!=11! = 1
  • 2!=2×1=22! = 2 \times 1 = 2
  • 3!=3×2×1=63! = 3 \times 2 \times 1 = 6
  • 4!=4×3×2×1=244! = 4 \times 3 \times 2 \times 1 = 24
  • 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120

The factorial of zero is defined as 1.

Factorials are commonly used in mathematics, permutations, combinations, probability, and programming exercises.

1. Python Program to Find Factorial Using a For Loop

The for loop is one of the easiest methods to calculate the factorial of a number in Python.

Program

num = int(input("Enter a number: "))

factorial = 1

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    for i in range(1, num + 1):
        factorial *= i

    print("Factorial of", num, "is", factorial)

Output 1

Enter a number: 5
Factorial of 5 is 120

Output 2

Enter a number: 6
Factorial of 6 is 720

Explanation

Let’s understand the program step by step.

Step 1: Get input from the user

num = int(input("Enter a number: "))

The input() function accepts a number from the user. The int() function converts the input into an integer.

Step 2: Initialize the factorial variable

factorial = 1

The variable factorial stores the result. It starts at 1 because multiplying by 1 does not change the result.

Step 3: Check for negative numbers

if num < 0:

Factorial is not defined for negative integers in the usual non-negative integer factorial definition.

Step 4: Calculate factorial using a loop

for i in range(1, num + 1):
    factorial *= i

The loop multiplies the factorial variable by each integer from 1 to num.

For the input 5, the calculation is:

IterationValue of iFactorial
111
222
336
4424
55120

Step 5: Display the result

print("Factorial of", num, "is", factorial)

The program displays the calculated factorial.

2. Python Program to Find Factorial Using a While Loop

You can also calculate factorial using a while loop. This approach is useful for understanding how loop conditions and counters work.

Program

num = int(input("Enter a number: "))

factorial = 1
i = 1

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    while i <= num:
        factorial *= i
        i += 1

    print("Factorial of", num, "is", factorial)

Output

Enter a number: 4
Factorial of 4 is 24

Explanation

The variable i begins at 1.

The while loop runs as long as i is less than or equal to the input number.

During every iteration:

  • Multiply factorial by i.
  • Increase i by 1.
  • Repeat until the condition becomes false.

For input 4, the calculations are:

factorial = 1 * 1 = 1
factorial = 1 * 2 = 2
factorial = 2 * 3 = 6
factorial = 6 * 4 = 24

The final result is 24.

3. Python Program to Find Factorial Using a Function

Functions allow you to reuse factorial logic in different parts of a program.

Program

def factorial(num):
    if num < 0:
        return None

    result = 1

    for i in range(1, num + 1):
        result *= i

    return result

n = int(input("Enter a number: "))

result = factorial(n)

if result is None:
    print("Factorial does not exist for negative numbers")
else:
    print("Factorial of", n, "is", result)

Output

Enter a number: 7
Factorial of 7 is 5040

Explanation

The function factorial(num) accepts a number as an argument.

If the number is negative, the function returns None.

Otherwise, it initializes result to 1 and uses a for loop to calculate the factorial.

The return statement sends the calculated value back to the main program.

Using functions makes the code more organized and reusable.

4. Python Program to Find Factorial Using Recursion

Recursion is a technique in which a function calls itself to solve a smaller version of the same problem.

The mathematical definition of factorial can be written as:n!=n×(n−1)!n! = n \times (n-1)!

with the base condition:0!=10! = 1

Program

def factorial(n):
    if n < 0:
        return None
    elif n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

num = int(input("Enter a number: "))

result = factorial(num)

if result is None:
    print("Factorial does not exist for negative numbers")
else:
    print("Factorial of", num, "is", result)

Output

Enter a number: 5
Factorial of 5 is 120

Explanation

The recursive function uses three conditions.

Condition 1: Negative number

if n < 0:
    return None

Negative numbers are not accepted by this program.

Condition 2: Base condition

elif n == 0 or n == 1:
    return 1

The factorial of 0 and 1 is 1. This condition stops further recursive calls.

Condition 3: Recursive calculation

return n * factorial(n - 1)

The function calls itself with a smaller number until it reaches the base condition.

For 5, the function evaluates:

5 * factorial(4)
5 * 4 * factorial(3)
5 * 4 * 3 * factorial(2)
5 * 4 * 3 * 2 * factorial(1)
5 * 4 * 3 * 2 * 1
120

Recursion is useful for understanding mathematical definitions and recursive problem-solving.

5. Python Program to Find Factorial Using the Math Module

Python provides a built-in math module with a factorial() function.

This is one of the shortest ways to calculate a factorial.

Program

import math

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    result = math.factorial(num)
    print("Factorial of", num, "is", result)

Output

Enter a number: 8
Factorial of 8 is 40320

Explanation

The math module contains mathematical functions.

The statement:

import math

imports the module.

The expression:

math.factorial(num)

calculates the factorial of a non-negative integer.

This method is concise and suitable when you want to use Python’s standard library rather than implement the algorithm manually.

6. Python Program to Find Factorial Without Using a Loop

You can calculate factorial without an explicit loop by using recursion or the math module.

Here is an example using recursion.

Program

def fact(n):
    if n == 0 or n == 1:
        return 1
    return n * fact(n - 1)

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    print("Factorial of", num, "is", fact(num))

Output

Enter a number: 3
Factorial of 3 is 6

Explanation

The function calls itself until the value reaches 1 or 0.

For the input 3:

fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1

Therefore:

3 * 2 * 1 = 6

Although the program does not use a loop, recursion still performs repeated function calls.

7. Python Program to Find Factorial of Multiple Numbers

You can calculate factorials for several numbers using a loop and a function.

Program

def factorial(n):
    result = 1

    for i in range(1, n + 1):
        result *= i

    return result

numbers = [3, 4, 5, 6]

for num in numbers:
    print("Factorial of", num, "is", factorial(num))

Output

Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720

Explanation

The list numbers stores four integer values.

The for loop takes each number and passes it to the factorial() function.

The function calculates and returns the factorial of each number.

This approach is useful when processing multiple inputs or calculating factorials in a larger program.

8. Python Program to Find Factorial Using a Single Line

Python also supports compact expressions. However, a short program is not always the easiest program to understand.

Using the math module, you can calculate a factorial in a single expression.

Program

import math

print(math.factorial(int(input("Enter a number: "))))

Output

Enter a number: 5
120

Explanation

The program performs three operations:

  1. Accepts input.
  2. Converts the input to an integer.
  3. Passes the number to math.factorial() and prints the result.

This compact method is useful for quick calculations, but the longer versions are better for learning loops and factorial logic.

9. Python Program to Find Factorial Using a List

A list can store the sequence of multiplication values used to calculate a factorial.

Program

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    values = list(range(1, num + 1))
    result = 1

    for value in values:
        result *= value

    print("Factorial of", num, "is", result)

Output

Enter a number: 5
Factorial of 5 is 120

Explanation

The range() function creates a sequence of numbers from 1 to num.

The list() function converts the sequence into a list.

The loop multiplies each value in the list to calculate the factorial.

For 5, the list is:

[1, 2, 3, 4, 5]

The final result is:

120

This method is useful for practicing lists and loops together, although creating a list is unnecessary for a simple factorial calculation.

10. Python Program to Find Factorial Using the Reduce Function

Python’s functools module provides the reduce() function, which repeatedly combines values from an iterable.

You can use it to calculate factorial.

Program

from functools import reduce

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    result = reduce(lambda x, y: x * y, range(1, num + 1), 1)
    print("Factorial of", num, "is", result)

Output

Enter a number: 5
Factorial of 5 is 120

Explanation

The reduce() function processes values from the sequence one by one.

The lambda expression:

lambda x, y: x * y

multiplies the current accumulated result by the next value.

The final argument 1 is the initial value. It also ensures that the result for zero is 1 because the range is empty when num is 0.

This method is useful for learning functional programming concepts in Python.

11. Python Program to Find Factorial of Zero

The factorial of zero is always 1.

This is a special mathematical rule and an important case in factorial programs.

Program

num = int(input("Enter a number: "))

if num == 0:
    print("Factorial of 0 is 1")
elif num < 0:
    print("Factorial does not exist for negative numbers")
else:
    result = 1

    for i in range(1, num + 1):
        result *= i

    print("Factorial of", num, "is", result)

Output

Enter a number: 0
Factorial of 0 is 1

Explanation

When the input is zero, the program directly displays 1.

For positive numbers, it uses the regular multiplication loop.

This example helps you understand why edge cases should be considered when writing programs.

12. Python Program to Find Factorial of a Large Number

Python integers can represent very large values, limited mainly by available memory and processing resources. You can calculate large factorials using a loop.

Program

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial does not exist for negative numbers")
else:
    result = 1

    for i in range(1, num + 1):
        result *= i

    print("Factorial of", num, "is", result)

Output

Enter a number: 20
Factorial of 20 is 2432902008176640000

Explanation

The program uses the same loop method, but the input is larger.

Python integers automatically support arbitrary precision, so the result is not restricted to the fixed integer sizes used by some other programming languages.

However, factorials grow very quickly. Calculating and printing extremely large factorials can require significant time and memory.

13. Factorial Program Using an Iterative Function

An iterative function uses loops rather than recursive calls.

This method is often easy to understand and avoids recursion depth limitations.

Program

def find_factorial(n):
    result = 1

    for number in range(2, n + 1):
        result = result * number

    return result

num = int(input("Enter a number: "))

if num < 0:
    print("Factorial is not defined for negative integers")
else:
    print("Factorial:", find_factorial(num))

Output

Enter a number: 10
Factorial: 3628800

Explanation

The function starts with result = 1.

It loops from 2 through the given number and multiplies each value into the result.

Starting at 2 is valid because multiplying by 1 does not change the result.

For input 10, the final result is 3,628,800.

14. Factorial Calculation Step by Step

Understanding the calculation process helps you write factorial programs more confidently.

For example, the factorial of 5 is:5!=5×4×3×2×15! = 5 \times 4 \times 3 \times 2 \times 1

The multiplication can be performed in stages.

StepCalculationResult
11 × 11
21 × 22
32 × 36
46 × 424
524 × 5120

Therefore:5!=1205! = 120

The loop-based Python program follows exactly this process.

15. Algorithm to Find Factorial

An algorithm is a sequence of steps used to solve a problem.

Algorithm:

  1. Start.
  2. Read an integer num.
  3. If num is negative, display an error message.
  4. Otherwise, initialize factorial = 1.
  5. Repeat for every integer i from 1 to num.
  6. Multiply factorial by i.
  7. Display the factorial.
  8. Stop.

For the input 4, the algorithm performs these calculations:

factorial = 1
factorial = 1 * 1
factorial = 1 * 2
factorial = 2 * 3
factorial = 6 * 4

The output is 24.

16. Flowchart Logic for Factorial

The following flowchart represents the logic of a factorial program.

        Start
          |
      Read num
          |
      num < 0?
       /     \
     Yes      No
      |        |
  Display    Set factorial = 1
  error             |
      |        Set i = 1
      |             |
      |         i <= num?
      |          /    \
      |        Yes     No
      |         |       |
      |   factorial =   Display
      |   factorial*i   result
      |         |
      |       i = i + 1
      |         |
      |     Repeat loop
      |         |
      +-------- End

The flowchart shows the input validation, loop condition, multiplication, and final output.

17. Time Complexity of Factorial Programs

Time complexity describes how the execution time grows as the input size increases.

MethodTime ComplexityExtra Space
For loopO(n)O(1)
While loopO(n)O(1)
Iterative functionO(n)O(1)
RecursionO(n)O(n) call stack
math.factorial()Implementation-dependentImplementation-dependent

For a simple iterative factorial program, the loop executes approximately n times. Therefore, its time complexity is O(n).

The recursive method also performs O(n) calls, but it uses additional stack memory for those calls.

The math.factorial() function is implemented in Python’s standard library and may use optimized internal algorithms. Its exact performance characteristics depend on the Python implementation and input size.

18. Common Mistakes in Factorial Programs

Beginners may make the following mistakes when writing factorial programs.

Mistake 1: Initializing the Result to Zero

Incorrect:

factorial = 0

If the result starts at zero, multiplying it by any number will keep it at zero.

Correct:

factorial = 1

Mistake 2: Forgetting the Zero Case

The factorial of zero is 1. A correct program should handle this case.

A loop from 1 to num naturally handles zero when the result is initialized to 1.

Mistake 3: Using an Incorrect Range

Incorrect:

for i in range(1, num):

This range excludes the input number.

Correct:

for i in range(1, num + 1):

The + 1 includes num in the loop.

Mistake 4: Accepting Negative Integers Without Validation

The usual factorial definition for non-negative integers does not include negative integers.

Check the input before starting the calculation.

Mistake 5: Forgetting to Update the Loop Variable

In a while loop, forgetting to increment the counter may create an infinite loop.

Always update the counter so the loop can eventually stop.

Mistake 6: Missing the Base Condition in Recursion

Recursive factorial programs need a base condition such as n == 0 or n == 1.

Without a base condition, the function continues calling itself until an error occurs.

19. Practice Questions on Factorial in Python

Try these exercises to improve your understanding of loops, functions, and recursion.

  1. Write a Python program to find the factorial of 5.
  2. Write a Python program to calculate factorial using a while loop.
  3. Write a Python program to find factorial using recursion.
  4. Write a Python function to calculate the factorial of a number.
  5. Write a Python program to find factorial using the math module.
  6. Write a Python program to calculate factorials for numbers from 1 to 10.
  7. Write a Python program to find the factorial of zero.
  8. Write a Python program to handle negative input when calculating factorial.
  9. Write a Python program to calculate factorial without using recursion or a built-in factorial function.
  10. Write a Python program that accepts multiple numbers and displays the factorial of each.

Practice Example: Factorials from 1 to 5

for num in range(1, 6):
    result = 1

    for i in range(1, num + 1):
        result *= i

    print("Factorial of", num, "is", result)

Output:

Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

This program uses nested loops to calculate the factorial of each number from 1 to 5.

20. Frequently Asked Questions

Q1. What is factorial in Python?

Factorial is the product of all positive integers from 1 up to a given non-negative integer. It is represented by the symbol !.

For example, 5! = 120.

Q2. How do you find factorial in Python?

You can use a for loop, a while loop, recursion, or Python’s built-in math.factorial() function.

Q3. What is the factorial of 0?

The factorial of zero is 1.

Q4. Can factorial be calculated using a while loop?

Yes. Initialize the result to 1 and use a while loop to multiply all integers from 1 through the given number.

Q5. What is the difference between iterative and recursive factorial programs?

An iterative program uses a loop to calculate factorial. A recursive program uses a function that calls itself with smaller values until it reaches a base condition.

Q6. Which method is easiest for beginners?

The for loop method is generally easy for beginners because the multiplication steps are visible and straightforward.

Q7. What is the time complexity of a factorial program?

A simple loop-based factorial program has O(n) time complexity because it performs a number of multiplications proportional to the input number.

Q8. Can Python calculate large factorials?

Yes. Python supports arbitrarily large integers, subject to available memory and processing resources.

Q9. Why is factorial used in programming?

Factorials are used in mathematical calculations involving permutations, combinations, probability, and other problems. They are also useful for learning loops and recursion.

Q10. Which Python module provides a factorial function?

The math module provides the math.factorial() function for calculating factorials of non-negative integers.

Conclusion

A Python program to find factorial is an important beginner-level programming exercise. It helps students understand loops, functions, recursion, conditional statements, and mathematical operations.

You have learned how to calculate factorial using for loops, while loops, functions, recursion, the math module, and other approaches. You have also explored algorithms, flowchart logic, time complexity, common mistakes, and practice questions.

Start by writing the simple for loop program. Then try the recursive method and the built-in function to understand the differences. Practicing these examples will help you prepare for Python practical exams, assignments, and coding interviews.

🔴Related Post

Leave a Comment