Table of Contents

Calculate the Factorial of a Number | Pictoblox

Example Description
This Python program uses a for loop nested inside an if...else block to calculate the factorial of a given number.

Introduction:

This Python program calculates the factorial of a given number using a for loop nested inside an if…else block. It first checks if the number is negative, positive, or zero, and then calculates the factorial accordingly.

Code:

#The following program uses a for loop nested inside an if..else 
#block to calculate the factorial of a given number
num = int(input("Enter a number: "))
fact = 1
# check if the number is negative, positive or zero
if num < 0:
 print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
 print("The factorial of 0 is 1")
else:
 for i in range(1, num + 1): 
  fact = fact * i
 print("factorial of ", num, " is ", fact)

Logic:

  1. Prompt the user to enter a number.
  2. Initialize a variable “fact” to 1.
  3. Check if the number is negative. If so, print a message stating that the factorial does not exist for negative numbers.
  4. If the number is 0, print a message stating that the factorial of 0 is 1.
  5. If the number is positive, use a for loop to iterate from 1 to the given number and calculate the factorial by multiplying the current value of “fact” with the loop variable “i”.

Output:

Enter a number: 3

>> factorial of 3 is 6