ByteBoard Notes Notes

Find the factorial of a positive number using a while loop

Computer Science XI · Experiment 10 of 27 · Python

11-CSPython programs
Expt. No.10
Page No.20

Factorial using while

Aim

To write a Python program that finds the factorial of a positive number using a while loop.

Concepts used

Algorithm

  1. Input a number.
  2. If it is negative, display that factorial is not defined.
  3. Otherwise set fact = 1 and i = 1.
  4. While i ≤ number, multiply fact by i and increase i by 1.
  5. Display fact.

Program

# Factorial of a number using a while loop num = int(input("Enter a positive number: "))if num < 0:    print("Factorial is not defined for negative numbers")else:    fact = 1    i = 1    while i <= num:        fact = fact * i        i = i + 1    print("Factorial of", num, "is", fact)

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python factorial_while_loop.py
Enter a positive number: 6 Factorial of 6 is 720
Run 2
$ python factorial_while_loop.py
Enter a positive number: 0 Factorial of 0 is 1

✓ Printed by running this program, not typed by hand.

Result

The factorial of 6 was 720 (1×2×3×4×5×6), and the factorial of 0 was 1, because the loop body did not run at all for 0.

Viva voce: what the examiner may ask

01Why does the program give 1 for 0!?

For 0 the condition i <= num is false at once, so fact keeps its starting value 1, which is the definition of 0!.

02What happens if you forget i = i + 1?

The condition never becomes false, so the loop runs forever (an infinite loop).

03When is a while loop better than a for loop?

When the number of repetitions is not known in advance and depends on a condition.

Variations for the lab test

  1. Write the same program with a for loop and range().
  2. Print each step, e.g. "1 × 2 = 2".
  3. Find the factorial using math.factorial() and compare.
! Common mistake Starting with fact = 0 makes every factorial 0, because any number multiplied by 0 is 0.
Back to the 11-CS index