Table of Contents

Python Code to Calculate Factorial

Example Description
This Python code calculates the factorial of a given number using a for loop and displays the result

Brief Introduction:

This Python code calculates the factorial of a given number using a for loop and displays the result.

Code:

#Function to calculate factorial
#The requirements are listed below:
 #1. The function should accept one integer argument from user.
 #2. Calculate factorial. For example:
 #3. Display factorial
def calcFact(num):
 fact = 1
 for i in range(num,0,-1):
  fact = fact * i
 print("Factorial of",num,"is",fact)
 
num = int(input("Enter the number: "))
calcFact(num)

Logic:

  1. The code defines a function named ‘calcFact’ that accepts one integer argument ‘num’.
  2. It initializes a variable ‘fact’ to 1.
  3. Then, it runs a for loop starting from ‘num’ and decreasing by 1 each time.
  4. Inside the loop, it updates the ‘fact’ variable by multiplying it with the current iteration value.
  5. Finally, it prints the factorial of the input number by displaying the value of ‘num’ and ‘fact’.

Output:

The code prompts the user to enter a number, calculates the factorial of the input number using the ‘calcFact’ function, and displays the factorial as “Factorial of [num] is [fact]”.

Enter the number: 10

>> Factorial of 10 is 3628800