Factorial of a Number in Python

Factorial of a Number in Python

Here we will discuss how to find the Factorial of a Number in Python programming language.

Factorial of any number is the product of it and all the positive numbers below it for example factorial of 5 is 120

Factorial of n (n!) = 1 * 2 * 3 * 4....n

5! = 1 x 2 x 3 x 4 x 5 = 120 7! = 1 x 2 x 3 x 4 x 5 x 6 x 7 = 5040

Factorial of a number

Algorithm for Factorial of a number

  • Input a number n.

  • Check if n < 0 → If true, print “Factorial not defined for negative numbers” and stop.

  • If n is 0 or 1 → Set factorial = 1.

  • Else, initialize factorial = 1 and run a loop from i = 2 to n, multiplying factorial *= i in each iteration.

  • Print the value of factorial as the result.

Methods of Factorial of a Number in Python

Ways discussed:

  • Iterative approach
  • Recursive approach
  • Factorial of a number in python using for loop
  • Factorial of a number using while loop
  • Factorial of a number in python using user input
  • Factorial of a number using if else
factorial in python

Method 1 (Iterative)

Python Code

Run

num = 6
fact = 1

# Factorial of negative number doesn't exist

if num < 0:
    print("Not Possible")
else:
    for i in range(1, num+1):
        fact = fact * i

print("Factorial of", num, "is", fact)
# Time complexity: O(N)
# Space complexity: O(1)

Output

Factorial of 6 is 720

Method 2 (Recursive)

This method uses recursion in Python

Python Code

Run

def getFactorial(num):
    if num == 0:
        return 1

    return num * getFactorial(num - 1)


num = 6
fact = getFactorial(num)

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

# Time complexity: O(N)
# Space complexity: O(1)
# Auxiliary Space complexity(Function call stack): O(N)

Output

Factorial of 6 is 720

Method 3 (Factorial Using for Loop)

Python Code

Run
num = 5
factorial = 1

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

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

Output

Factorial of 5 is 120

Explanation:

  • We start with factorial = 1.
  • range(1, num + 1) gives numbers from 1 to 5.
  • We multiply factorial with every number in that range.

Method 4 (Factorial Using while Loop)

Python Code

Run
# Factorial using while loop

num = 5
factorial = 1
i = 1

while i <= num:
    factorial *= i
    i += 1

print(f"Factorial of {num} is {factorial}")

Output

Factorial of 5 is 120

Explanation:

  • Initialize factorial = 1 and start a counter i = 1.
  • Use while loop to multiply factorial with each number up to num.
  • Print the result once the loop finishes.

Method 5 (Factorial Using User Input)

Python Code

Run

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(f"Factorial of {num} is {factorial}")

Output

Factorial of 6 is 720

Explanation:

  • Take input from user using input() and convert it to an integer.

  • Use for loop from 1 to num, multiplying each value to get factorial.

  • Add a condition to handle negative inputs gracefully.

Method 6 (Factorial Using if-else)

Python Code

Run
num = 4
factorial = 1

if num < 0:
    print("Factorial is not defined for negative numbers")
elif num == 0 or num == 1:
    print(f"Factorial of {num} is 1")
else:
    for i in range(2, num + 1):
        factorial *= i
    print(f"Factorial of {num} is {factorial}")

Output

Factorial of 4 is 24

Explanation:

  • Use if-else to check special cases like negative numbers or 0/1.

  • Calculate factorial using a loop only when number > 1.

  • Print the result using formatted output.

Final Words

Understanding how to calculate the factorial of a number in Python is a foundational concept that introduces you to loops, conditionals, recursion, and user input handling. It’s a great exercise to improve logical thinking and control flow mastery in Python.

By exploring various methods like iterative, recursive, and conditional approaches, you gain flexibility in solving problems using different programming styles. Each method has its unique use case, whether you’re optimizing for readability, performance, or user interaction.

For similar Questions click on the given button

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

FAQs

The time complexity is O(n) and space complexity is O(1), since it uses a single loop and constant space.

No, factorial is not defined for negative numbers. Always validate the input before processing.

Iterative uses loops for calculation, while recursive calls the function within itself. Recursion uses more memory due to the call stack.

Use input() to take a number, convert it to int, check for valid input, and then use a loop or recursion to calculate the factorial.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

2 comments on “Factorial of a Number in Python”