Algorithm


Input:
     Accept a number as input from the user.

Function Definition:
     Define a function factorial that takes a parameter n.

Base Case:
     If n is 0 or 1, return 1 (base case for factorial).

Recursive Case:
     If n is greater than 1, calculate n! recursively as n * factorial(n-1).

User Input:
     Take a number from the user as input.

Calculate Factorial:
     Call the factorial function with the user-input number.

Output:
     Print the result, indicating the factorial of the input number.

Code Examples

#1 Example- Write a Python program to calculate the factorial of a number input by the user using the factorial () function.

Code - Python Programming


import math

n = int (input (“Enter the number whose factorial you want to find: ”))

print (“The factorial of the number is: “)

print (math.factorial (n))
Copy The Code & Try With Live Editor

#2 Example - Write a program to calculate the factorial of a number in Python using FOR loop.

Code - Python Programming


n = int (input (“Enter a number: “))

factorial = 1

if n >= 1:

              for i in range (1, n+1):

                             factorial = factorial *i

print (“Factorial of the given number is: “, factorial)
Copy The Code & Try With Live Editor

#3 Code Example with Python Programming

Code - Python Programming


n = int (input (“Enter the number for which the factorial needs to be calculated: “)

factorial = 1

if n < 0:

              print (“Factorial cannot be calculated, non-integer input”)

elif n == 0:

              print (“Factorial of the number is 1”)

else:

              for i in range (1, n+1):

                             factorial = factorial *i

              print (“Factorial of the given number is: “, factorial)
Copy The Code & Try With Live Editor

#4 Example- Write the Python program to calculate the factorial of a number using recursion.

Code - Python Programming


n = int (input (“Enter the number for which the factorial needs to be calculated: “)

def rec_fact (n):

              if n == 1:

                             return n

elif n < 1:

              return (“Wrong input”)

else:

              return n*rec_fact (n-1)

print (rec_fact (n))
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Python Programing Example to Find the Factorial of a Number-DevsEnv