Write a Python program that calculates the factorial of a given number using recursion

SOLUTION.

# Function to calculate factorial using recursion
def factorial(n):
    if n == 0 or n == 1:  # Base case
        return 1
    return n * factorial(n - 1)  # Recursive case

# Taking dynamic input from the user
num = int(input("Enter a number: "))

# Checking if the number is non-negative
if num < 0:
    print("Factorial is not defined for negative numbers.")
else:
    # Calculating factorial
    result = factorial(num)
    print(f"The factorial of {num} is: {result}")
    

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.