make me a simple python program with documentation
- User
make me a simple python program with documentation
Assistant
Here's a simple Python program that calculates the factorial of a number, with documentation:
def factorial(n): """ This function calculates the factorial of a number. :param n: An integer for which the factorial is calculated. :type n: int :return: The factorial of the input number. :rtype: int :raises TypeError: If the input is not an integer. :raises ValueError: If the input is less than 0. """ if not isinstance(n, int): raise TypeError("Input must be an integer.") if n < 0: raise ValueError("Input must be a non-negative integer.") result = 1 for i in range(1, n + 1): result *= i return result # Example usage: try: num = int(input("Enter a number: ")) print(f"The factorial of {num} is {factorial(num)}.") except ValueError as e: print(e) except TypeError as e: print(e)The
factorialfunction accepts an integer as input and returns the factorial of that number. If the input is not an integer, it raises aTypeError. If the input is less than 0, it raises aValueError. The function uses a simple for loop to calculate the factorial.The example usage section demonstrates how to call the function with user input. It also includes error handling for 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.