Factorial of Each Number 1-N
Calculate and print a factorial for every integer through n. Students trace Python nested loops and reset each inner product before multiplying its factors.
1# Take n2n = int(input("Enter n: "))34# Print factorials5for i in range(1, n + 1):6 fact = 17 for j in range(1, i + 1):8 fact *= j9 print(f"{i}! = {fact}")
Output
Enter n: 5 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120
In this one
- Reset a nested product
- Recompute each factorial
- Label each completed result
How it works
- 1
Choose i from one through n.
- 2
Initialize fact and multiply one through i.
- 3
Print that factorial before the next outer iteration.
Edge cases
Is 0! printed?
Is 0! printed?
No. The outer loop starts at one.
What if fact were not reset?
What if fact were not reset?
Later rows could multiply in previous products and give wrong values.
What's going on
The outer loop selects which factorial to calculate. For each i, fact starts at one again before the inner loop multiplies one through i.
With n equal to three, the output gives 1!, 2!, and 3! as one, two, and six. This intentionally recomputes each factorial to practice nested loops; it is not a running-product optimization. Reset placement prevents earlier factorials from multiplying into later ones.
Is 0! printed? No. The outer loop starts at one.
What if fact were not reset? Later rows could multiply in previous products and give wrong values.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
How is 3! calculated here?
Pick an answer to check it.
Question 2
Is 0! printed?
Pick an answer to check it.
Questions people ask
Is 0! printed?
No. The outer loop starts at one.
What if fact were not reset?
Later rows could multiply in previous products and give wrong values.
How is 3! calculated here?
1 * 2 * 3.
๐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