Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to return the factorial of a number - Python Program

Example 1 :

def factorial(n): """Return factorial of n.""" result = 1 for i in range(1, n+1): result *= i return result print(factorial(5))

Output

 
OUTPUT  :
120
 

Example 2 : Advanced Program

def factorial_iterative(n): """ Calculates the factorial of a non-negative integer iteratively. Args: n: The non-negative integer for which to calculate the factorial. Returns: The factorial of n. """ if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer.") if n == 0: return 1 result = 1 for i in range(1, n + 1): result *= i return result # Example Usage and Output number = 5 print(f"The factorial of {number} is {factorial_iterative(number)}") number_zero = 0 print(f"The factorial of {number_zero} is {factorial_iterative(number_zero)}")

Output

 
OUTPUT  :
The factorial of 5 is 120
The factorial of 0 is 1
 

Explanation

This function, factorial_iterative, calculates the factorial by initializing a result variable to 1. It then iterates from 1 up to and including the input number n, multiplying result by each number in the loop. This process directly computes the product of all positive integers less than or equal to n. It handles the base case of 0! (factorial of 0) being 1. It also includes error handling for invalid inputs (negative numbers or non-integers). 

Example 3 : Advanced Program - Recursive Function

def factorial_recursive(n): """ Calculates the factorial of a non-negative integer recursively. Args: n: The non-negative integer for which to calculate the factorial. Returns: The factorial of n. """ if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer.") # Base case: Factorial of 0 or 1 is 1 if n == 0 or n == 1: return 1 # Recursive step: n * factorial of (n-1) else: return n * factorial_recursive(n - 1) # Example Usage and Output number = 4 print(f"The factorial of {number} is {factorial_recursive(number)}") number_one = 1 print(f"The factorial of {number_one} is {factorial_recursive(number_one)}")

Output

 
OUTPUT  :
The factorial of 4 is 24
The factorial of 1 is 1
 

Explanation

The factorial_recursive function defines the factorial based on its recursive definition: n! = n * (n-1)!. It has a base case where the factorial of 0 or 1 is 1, which stops the recursion. For any other positive integer n, it calls itself with n-1 and multiplies the result by n. This approach breaks down the problem into smaller, similar sub-problems until the base case is reached. It also includes error handling for invalid inputs.