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

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.

BeginnerPhase 2 - Level 1: Basic LoopingExample 4 of 14
print-the-factorial-of-a-given-number.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate factorial
5factorial = 1
6for i in range(1, n + 1):
7 factorial *= i
8
9print(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. 1

    Start factorial at one.

  2. 2

    Multiply by each factor one through n.

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