How to write a factorial function in Python?
- User
How to write a factorial function in Python?
- Assistant
To write a factorial function in Python, you can use either an iterative approach or a recursive approach. Here are examples of both:
- Iterative Approach:
def factorial(n): if n < 0: return None result = 1 for i in range(1, n + 1): result *= i return resultExplanation:
- The function takes a non-negative integer
nas input. - If
nis negative, the function returns to indicate an invalid input.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.