Programs · Program 6-19
Q.Program 6-19: Write a program to calculate the factorial of a given number.
Telangana TsbieTextbookSubjective· 3mImportance★★★★★est
59% · 23/39 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Keep a running product fact (initialised to 1) and multiply it by every integer from 1 to n in a for loop — for the input 5 the program prints 120.
The idea. The factorial n! = 1 × 2 × 3 × … × n is the multiplicative twin of a running sum: instead of adding into an accumulator that starts at 0, we multiply into an accumulator that starts at 1 (the identity for multiplication). A counting for loop supplies the integers 1…n.
# Program 6-19: calculate the factorial of a given number
num = int(input("Enter a number: "))
fact = 1
if num < 0:
print("Factorial is not defined for negative numbers")
else:
for i in range(1, num + 1):
fact = fact * i
print("Factorial of", num, "is", fact)
Sample run (user enters 5)
Enter a number: 5
Factorial of 5 is 120
Dry run for num = 5
i | fact before | fact = fact * i |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 6 |
| 4 | 6 | 24 |
| 5 | 24 | 120 |
Edge cases handled
num = 0:range(1, 1)is empty, the loop body never runs, andfactremains 1 — which is exactly the mathematical convention 0! = 1. …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.