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.
- Factorial of 5 is: 5 × 4 × 3 × 2 × 1 = 120
- Factorial of 3 is: 3 × 2 × 1 = 6
Step-by-Step Algorithm
- Take a number as input.
- Initialize factorial variable as 1.
- Use a loop from 1 to the number.
- Multiply factorial by each number.
- 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
- input() takes user input.
- factorial variable stores result.
- range(1, number + 1) generates loop values.
- Multiplication is repeated inside loop.
- Final factorial value is displayed.
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
- Permutations and combinations
- Probability calculations
- Mathematics and statistics
- Algorithm analysis
- Competitive programming
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.