GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Basic-python-programs/factorial.py at main · Sbiswas001/Basic-python-programs Expand file tree/ Copy pathfactorial.pyMore file actions 83 lines (60 loc) · 1.91 KB / Copy pathfactorial.pyFile metadata and controls83 lines (60 loc) · 1.91 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 """ Factorial Program This program calculates the factorial of a given number. Factorial of n (n!) = n * (n-1) * (n-2) * ... * 1 """ def factorial(n): """ Calculate the factorial of a number. Args: n (int): A non-negative integer Returns: int: The factorial of n Raises: ValueError: If n is negative TypeError: If n is not an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") if n < 0: raise ValueError("Factorial is not defined for negative numbers") if n == 0 or n == 1: return 1 result = 1 for i in range(2, n + 1): result *= i return result def factorial_recursive(n): """ Calculate the factorial of a number using recursion. Args: n (int): A non-negative integer Returns: int: The factorial of n Raises: ValueError: If n is negative TypeError: If n is not an integer """ if not isinstance(n, int): raise TypeError("Input must be an integer") if n < 0: raise ValueError("Factorial is not defined for negative numbers") if n == 0 or n == 1: return 1 return n * factorial_recursive(n - 1) if __name__ == "__main__": # Example usage print("Factorial Calculator") print("=" * 40) try: num = int(input("Enter a non-negative integer: ")) # Calculate using iterative method result_iterative = factorial(num) print(f"\nFactorial of {num} (iterative): {result_iterative}") # Calculate using recursive method result_recursive = factorial_recursive(num) print(f"Factorial of {num} (recursive): {result_recursive}") except ValueError as e: print(f"Error: {e}") except TypeError as e: print(f"Error: {e}") |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |