From ff70d3377424428415dae98b836ce4e164ba1d2a Mon Sep 17 00:00:00 2001 From: Junior Date: Mon, 3 Jun 2024 19:42:49 -0400 Subject: [PATCH] Simple recursion example --- Python/028_recursion.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/028_recursion.py diff --git a/Python/028_recursion.py b/Python/028_recursion.py new file mode 100644 index 0000000..19f1770 --- /dev/null +++ b/Python/028_recursion.py @@ -0,0 +1,36 @@ +# 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)) \ No newline at end of file