Write a simple Python function to calculate the factorial of a given positive integer.
- User
Write a simple Python function to calculate the factorial of a given positive integer.
- Assistant
Certainly! Here's a simple Python function that calculates the factorial of a given positive integer:
pythondef factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") elif n == 0: return 1 else: result = 1 for i in range(1, n + 1): result *= i return resultExplanation:
-
The function
factorialtakes a single parametern, which represents the positive integer for which we want to calculate the factorial. -
We start with a check to handle negative numbers. If
nis negative, we raise a with an appropriate error message since factorial is not defined for negative numbers.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.