Factorial in Python: Three Methods for Placement Tests
Three ways to write a factorial in Python: for loop, recursion with the correct base case, and math.factorial, with placement aptitude context.
A factorial program in Python has three common implementations, and only one of them handles zero input correctly without modification.
The connection to campus placements is direct: permutations and combinations questions in aptitude rounds depend on factorial computation at every step, and knowing which Python implementation to reach for, and why, is the working knowledge that placement coding sections expect.
Why Factorials Appear in Placement Aptitude Tests
The factorial of a non-negative integer n is the product of all positive integers from 1 to n. By convention, the factorial of 0 is 1.
Placement aptitude rounds at companies like TCS, Infosys, and Capgemini test permutations and combinations (P and C) heavily. Both formulas reduce to factorial division:
- Permutations of r items from n:
nPr = n! / (n-r)! - Combinations of r items from n:
nCr = n! / (r! * (n-r)!)
A candidate who can compute factorials quickly can verify P and C answers faster than someone working through long multiplication from scratch. In a timed aptitude round, that verification step often separates a correct answer from a careless one.
A Sample P&C Calculation
A common placement question type: “In how many ways can a committee of 3 students be selected from a group of 5?” This is a combinations problem.
- Formula:
5C3 = 5! / (3! * 2!) - Numerator: 5 multiplied by 4 multiplied by 3 multiplied by 2 multiplied by 1 = 120
- Denominator: (3 multiplied by 2 multiplied by 1) multiplied by (2 multiplied by 1) = 6 multiplied by 2 = 12
- Result: 120 divided by 12 = 10
Running math.factorial(5) // (math.factorial(3) * math.factorial(2)) in Python produces 10 in under a second. That kind of rapid verification is useful for sanity-checking hand calculations during practice sessions.
The Campus Placement Evaluation Test and similar structured aptitude formats typically include four to six P and C questions per section. The factorial formula runs beneath every one of them.
For a broader aptitude foundation, the Quantitative Aptitude guide on Time and Work demonstrates the same step-by-step calculation discipline that applies across different question types in placement rounds.
Method 1: The Iterative For Loop
The for-loop method is the recommended choice for placement coding rounds. It is readable, handles all edge cases with a single conditional at the start, and has no recursion-depth limit.
def factorial_loop(num):
if num < 0:
return "Invalid: negative input has no factorial"
factorial = 1
for i in range(1, num + 1):
factorial *= i
return factorial
print(factorial_loop(0)) # 1
print(factorial_loop(1)) # 1
print(factorial_loop(5)) # 120
print(factorial_loop(6)) # 720
How the Loop Handles Zero Input
For num = 0, the expression range(1, 0 + 1) evaluates to range(1, 1), which is empty. The loop body never executes, and the function returns the initial value of 1. This matches the mathematical convention that 0! = 1 without requiring any special-case branch.
Trace for factorial_loop(5):
- Start:
factorial = 1 i = 1: factorial = 1 multiplied by 1 = 1i = 2: factorial = 1 multiplied by 2 = 2i = 3: factorial = 2 multiplied by 3 = 6i = 4: factorial = 6 multiplied by 4 = 24i = 5: factorial = 24 multiplied by 5 = 120- Return: 120
The trace shows why the initial value must be 1, not 0: a 0 initial value collapses the entire product to 0 regardless of input.
The Single Most Common Starter Error
Starting factorial = 0 instead of factorial = 1 produces 0 for every positive input. The output looks superficially plausible for num = 0 (zero sits adjacent to the expected 1), which is why this bug survives an initial glance but fails on any nonzero test case. Setting the correct initial value before the loop is the one check that separates a working solution from a zero-returning one.
Method 2: Recursion and the Base-Case Fix
Recursion matches the mathematical definition of factorial directly:
n! = n * (n-1)!for n greater than 1- Base cases:
0! = 1and1! = 1
The version that appears in many older Python tutorials has a one-line bug:
# BUGGY — base case misses num = 0
def factorial_buggy(num):
if num == 1: # should be num <= 1
return 1
else:
return num * factorial_buggy(num - 1)
Calling factorial_buggy(0) does not reach the num == 1 branch. The function instead computes 0 * factorial_buggy(-1), then -1 * factorial_buggy(-2), and continues until Python’s default recursion limit (around 1000 frames) is exhausted, raising a RecursionError.
The outer if num == 0: print(...) guard in the original script prevents this crash in that specific context, but it means the function itself is not a correct standalone implementation. Any direct call to factorial_buggy(0) fails.
The fix is one change: replace == 1 with <= 1.
# FIXED — handles 0, 1, and all positive integers
def factorial_recursive(num):
if num < 0:
return "Invalid: negative input"
if num <= 1:
return 1
return num * factorial_recursive(num - 1)
print(factorial_recursive(0)) # 1
print(factorial_recursive(1)) # 1
print(factorial_recursive(5)) # 120
Recursion Trace for n = 4
factorial_recursive(4)calls4 * factorial_recursive(3)factorial_recursive(3)calls3 * factorial_recursive(2)factorial_recursive(2)calls2 * factorial_recursive(1)factorial_recursive(1)hits the base case and returns 1- Unwind: 2 multiplied by 1 = 2; 3 multiplied by 2 = 6; 4 multiplied by 6 = 24
- Final result: 24
The call stack grows one frame per recursive call. For large inputs, this matters.
Recursion Depth Limit
Python’s default recursion limit is around 1000 calls. factorial_recursive(1001) raises RecursionError: maximum recursion depth exceeded. The iterative method has no such constraint and is safe for any input size a placement question will realistically use. Reserve the recursive method for situations where demonstrating recursion understanding is explicitly part of the task.
Method 3: Python’s Built-in math.factorial
Python’s math module includes a factorial function that handles all edge cases, executes faster than a hand-written loop for large inputs, and raises a clear error for invalid inputs.
import math
print(math.factorial(0)) # 1
print(math.factorial(1)) # 1
print(math.factorial(5)) # 120
print(math.factorial(10)) # 3628800
# Negative input raises ValueError:
# math.factorial(-1) → ValueError
The Python official documentation specifies that math.factorial accepts a non-negative integer and raises ValueError for negative values and TypeError for non-integer arguments. This built-in is the most defensive option when the input source is not controlled.
In a placement coding round, math.factorial is appropriate when the question explicitly allows standard library imports. Most Python-based online judges used in campus placements at TCS NQT, Infosys InfyTQ, and Wipro’s recruitment portal allow import math. If the problem statement requires implementing factorial without built-in functions, use the iterative method instead.
Choosing the Right Method
Each method fits a specific context. The table below summarises the key differences:
| Method | Zero input | Negative check | Large n safety | Best for |
|---|---|---|---|---|
| For loop | Correct by default | One if at start | No stack limit | Placement rounds, custom logic |
| Recursion (fixed) | Correct with num <= 1 | Add before call | Stack limit ~1000 | Demonstrating recursion thinking |
math.factorial | Correct | Auto ValueError | Fastest option | Quick verification, import allowed |
For campus placements, the for-loop version covers most situations: it is the easiest to explain in a coding interview, the safest to adapt for edge cases like large inputs, and the one least likely to produce a surprise error.
IndiaBix Permutation and Combination practice has more than 80 problems where factorial computation is an intermediate step. Working through 20 to 30 of them with the for-loop method builds the pattern recognition that makes P and C questions predictable under timed conditions.
The Best Books for Placement Preparation article lists resources that students who clear aptitude rounds consistently use.
The three-method comparison above maps to three levels of engagement with any technical skill. Loop through the mechanics to verify the result, trace the recursion to build intuition, then reach for the built-in when speed matters more than custom behaviour. TinkerLLM at ₹299 applies the same approach to LLM fundamentals: run a prompt, trace the token logic, then ship a retrieval or tool-call pattern that terminates correctly.
Primary sources
Frequently asked questions
What is the factorial of 0 in Python?
By mathematical convention, 0 factorial equals 1. Python's math.factorial(0) returns 1. The iterative for-loop with range(1, 1) — an empty range — also returns 1 because the initial value is set to 1 before the loop executes.
Why does the recursive factorial function fail for input 0?
If the base case is `if num == 1: return 1`, calling factorial(0) misses the base case and recurses into factorial(-1), factorial(-2), and so on, causing a RecursionError. Fix: use `if num <= 1: return 1` as the base case to handle both 0 and 1.
Which factorial method should I use in a placement coding round?
Use the iterative for-loop with an explicit check for negative input. It is readable, handles all edge cases without recursion-depth limits, and executes efficiently for any n a placement test is likely to use.
Can Python handle large factorials without overflow?
Yes. Python integers have arbitrary precision, so math.factorial(1000) runs without error. C and Java overflow at n around 21 for standard 64-bit signed integers. This is one reason placement Python problems allow larger n values than equivalent C problems.
How do factorials connect to permutations and combinations in aptitude tests?
nPr equals n factorial divided by (n minus r) factorial. nCr equals n factorial divided by the product of r factorial and (n minus r) factorial. Every permutation and combination problem in a campus placement aptitude round reduces to these two formulas.
What does math.factorial raise for a negative input?
math.factorial raises a ValueError for any negative integer. It only accepts non-negative integers. Check for negative values in your own code before calling math.factorial if user input is involved.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)