Python Programs on Functions

Write a python program to

  1. find factorial of a given number using function.
  2. find factorial of a given number using Recursive function.

Factorial Definition: The factorial of a non-negative integer n (denoted n!) is the product of all positive integers less than or equal to n.
For example: 5! = 5 * 4 * 3 * 2 * 1 = 120

Logic:

  1. Use a loop to multiply numbers from 1 to n. Initialize a variable (e.g., result = 1). For each integer i from 1 to n, multiply result by i.
  2. factorial(n) = n * factorial(n-1) for n > 1.

Program:



########### (a) Factorial using iterative function ###########
def factorial_iterative(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
num = int(input("Enter a number to calculate its factorial: "))
print(f"Iterative Factorial of {num} is: {factorial_iterative(num)}")

Output:

Enter a number to calculate its factorial: 5
Iterative Factorial of 5 is: 120


############  (b) Factorial using recursive function ###########
def factorial_recursive(n):
    if n == 0 or n == 1:
        return 1
    return n * factorial_recursive(n - 1)
num = int(input("Enter a number to calculate its factorial: "))
print(f"Recursive Factorial of {num} is: {factorial_recursive(num)}")

Output:

Enter a number to calculate its factorial: 5
Iterative Factorial of 5 is: 120