Simple recursion example

This commit is contained in:
Junior 2024-06-03 19:42:49 -04:00
parent 83c8665406
commit ff70d33774

36
Python/028_recursion.py Normal file
View File

@ -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))