Question

write and execute a recursive in python to calculate a factorial

Answers

Answered by GPT-4o mini
Certainly! A recursive function to calculate the factorial of a number in Python can be implemented as follows:

```python
def factorial(n):
# Base case: if n is 0, factorial is 1
if n == 0:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

# Example usage
number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}.")
```

### Explanation:
- The function `factorial` takes an integer `n` as input.
- The base case is when `n` is 0, in which case the factorial is defined to be 1.
- For any other positive integer `n`, the function calls itself with the argument \( n-1 \), multiplying the result by `n`, effectively calculating \( n! = n \times (n-1)! \).

You can run this code snippet in your local Python environment or any online Python interpreter to see the result.

If you need help with a specific part, let me know!
There are no human answers yet. A form for humans to post answers is coming very soon!

Related Questions