Print the Factorial of a Given Number
Compute factorial with a multiplication loop. Students follow the initial value one, included factors, zero factorial, and the need to reject negative inputs.
1# Take n as input2n = int(input("Enter n: "))34# Calculate factorial5factorial = 16for i in range(1, n + 1):7 factorial *= i89print(f"Factorial of {n} is {factorial}")
Output
Enter n: 5 Factorial of 5 is 120
In this one
- Initialize a product
- Calculate factorial iteratively
- Explain zero factorial
How it works
- 1
Start factorial at one.
- 2
Multiply by each factor one through n.
- 3
Print the resulting product.
Edge cases
What is 0!?
What is 0!?
One; the initialized product survives the empty loop.
Is negative input validated?
Is negative input validated?
No. The code returns one even though the intended domain is nonnegative integers.
What's going on
Factorial multiplies the positive integers up to n. The accumulator begins at one because starting at zero would make every later multiplication zero.
range(1, n + 1) includes n. With n equal to four, the running product becomes one, two, six, then twenty-four. Zero uses an empty product, correctly giving one; negative inputs also skip the loop but do not have factorials in this lesson.
What is 0!? One; the initialized product survives the empty loop.
Is negative input validated? No. The code returns one even though the intended domain is nonnegative integers.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why initialize to one?
Pick an answer to check it.
Question 2
What is 0!?
Pick an answer to check it.
Questions people ask
What is 0!?
One; the initialized product survives the empty loop.
Is negative input validated?
No. The code returns one even though the intended domain is nonnegative integers.
Why initialize to one?
It is neutral for multiplication.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum