Welcome to Foundation of Data Science Laboratory
Welcome to Foundation of Data Science Laboratory
Write a Python program to find the factorial of a number using recursion
With Function
# Function to calculate factorial of a number
def factorial(n):
"""
This function returns the factorial of a given number n.
Factorial of n (n!) is the product of all positive integers less than or equal to n.
"""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage
number = 5 # You can change this number to test other values
result = factorial(number)
result
Write a Python program to find the factorial of a number using Iterative approach
# Function to calculate factorial of a number iteratively
def factorial_iterative(n):
"""
This function returns the factorial of a given number n using an iterative approach.
Factorial of n (n!) is the product of all positive integers less than or equal to n.
"""
if n < 0:
return "Factorial is not defined for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result
# Example usage
number = 5 # You can change this number to test other values
result = factorial_iterative(number)
result
# Function to calculate factorial of a number iteratively and read number from user
def factorial_iterative(n):
"""
This function returns the factorial of a given number n using an iterative approach.
Factorial of n (n!) is the product of all positive integers less than or equal to n.
"""
if n < 0:
return "Factorial is not defined for negative numbers"
result = 1
for i in range(1, n + 1):
result *= i
return result
# Take input from user
try:
number = int(input("Enter a number to calculate its factorial: "))
result = factorial_iterative(number)
print(f"The factorial of {number} is {result}.")
except ValueError:
print("Invalid input. Please enter an integer.")