|
| 1 | +--- |
| 2 | +title: Calculate Factiorial of a number |
| 3 | +description: Calculates factorial of a given number using recursive function |
| 4 | +author: SamratBarai |
| 5 | +tags: math,factorial,recursive-function |
| 6 | +--- |
| 7 | + |
| 8 | +```py |
| 9 | +def factorial(n): |
| 10 | + if type(n) != int or n < 0: raise ValueError("Invalid value of input: '" + str(n) + "'") # Raises an error for invalid input |
| 11 | + if n == 0 or n == 1: return 1 # Returns 1 if n is 0 or 1 |
| 12 | + else: return n * factorial(n-1) # Recall the factorial function |
| 13 | +``` |
| 14 | + |
| 15 | +# Usage: |
| 16 | +print(factorial(4)) # Returns 24 |
| 17 | +print(factorial(-3)) # Returns type error for invalid inputs |
0 commit comments