Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 8 of 12
factorial-of-each-number-1-n.py
1# Take n
2n = int(input("Enter n: "))
3
4# Print factorials
5for i in range(1, n + 1):
6 fact = 1
7 for j in range(1, i + 1):
8 fact *= j
9 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. 1

    Choose i from one through n.

  2. 2

    Initialize fact and multiply one through i.

  3. 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.