Python Factorial Program

Learn how to create a factorial program in Python using loops and beginner-friendly logic with complete explanations and examples.

Introduction

Factorial is one of the most common mathematical concepts used in programming and algorithms.

The factorial of a number is the product of all positive integers smaller than or equal to that number.

In this tutorial, you will learn how to create a factorial program in Python using loops and conditions.

Factorial programs are commonly asked in coding interviews and beginner programming exercises.

Problem Explanation

The goal is to calculate the factorial of a given number.

Step-by-Step Algorithm

  1. Take a number as input.
  2. Initialize factorial variable as 1.
  3. Use a loop from 1 to the number.
  4. Multiply factorial by each number.
  5. Display the final factorial value.

Python Program

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

factorial = 1

if number < 0:

    print("Factorial does not exist")

elif number == 0:

    print("Factorial of 0 is 1")

else:

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

        factorial = factorial * i

    print("Factorial is", factorial)

Code Explanation

Program Output

Example 1:

Enter a number: 5

Factorial is 120

Example 2:

Enter a number: 3

Factorial is 6

Common Mistakes

Mistake Problem
Wrong loop range Incorrect factorial result
Forgetting factorial = 1 Program gives wrong output
Not handling negative numbers Invalid factorial calculation

Optimization Tip

Factorial programs can also be created using recursion in Python.

Recursive factorial programs are frequently asked in interviews.

Real-World Uses of Factorial

Frequently Asked Questions

What is factorial?

Factorial is the multiplication of all positive integers from 1 to the given number.

What is factorial of 0?

Factorial of 0 is always 1.

Can factorial be negative?

No, factorial is not defined for negative numbers.

Conclusion

In this tutorial, you learned how to create a Python factorial program using loops and conditions.

This beginner-level problem improves understanding of loops, variables, and mathematical logic in Python.