Example output
Here's a code snippet in Python that accomplishes the specific task of finding the factorial of a given integer using a recursive function. The code is designed to be simple and follows best practices in Python. It also includes comments to explain each segment of the code and provides an alternative approach.
# Define a recursive function to calculate the factorial of a number
def factorial(n):
# Base case: if n is 0 or 1, the factorial is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n! = n * (n-1)!
return n * factorial(n - 1)
# Input: Prompt the user for an integer
n = int(input("Enter a non-negative integer: "))
# Check if the input is non-negative
if n < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculate and print the factorial
result = factorial(n)
print(f"{n}! = {result}")
Explanation:
We define a recursive function factorial that takes an integer n as input and calculates the factorial of n.
In the function, we have a base case: if n is 0 or 1, the factorial is 1.
In the recursive case, we calculate the factorial by multiplying n with the factorial of n-1.
We prompt the user to enter a non-negative integer.
We check if the input is non-negative, as factorials are not defined for negative numbers.
If the input is valid, we call the factorial function to calculate and print the result.
Alternative Approach:
An alternative approach to calculating the factorial is to use an iterative loop. This can be more efficient for large values of n as it avoids the overhead of function calls and stack usage. Here's an example of an iterative approach:
def factorial_iterative(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
You can use the factorial_iterative function as an alternative to the recursive approach if efficiency is a concern for large inputs.