# A simple demonstration of recursion # Recursion is the act of calling a function from # within itself. This is not often used, but super # handy for doing mathmatical work and walking # directory structures in a file system. # In this example we will recursively calculate the # factorial of a number. If you will remember from math # class a factorial is all the numbers from one to a # specified number multiplied together. # i.e 6 factorial is 1 * 2 * 3 * 4 * 5 * 6 # This is the recursive function. # It returns the parameter if it equals one # Otherwise it multiples the parameter by the results of # calling the function with the parameter reduced by one def factorial(n): if n == 1: return n else: return n * factorial(n-1) num = None while num is None: try: num = int(input("Enter a positive number: ")) if num < 0: num = None except: pass if num == 0: print("Factorial of 0 is 1") else: print(f"Factoial of {num} is", factorial(num))