Recursion

Lesson Progress
0% Complete

Calling function from inside the function

Factorial Function – using Recursion(definition)

def factorial_with_recursion(num):
    try:
        if num < 0: # check for negative number
            print("Sorry, factorial does not exist for negative numbers")
        elif num == 0: # check for zero 0 input
            print("The factorial of 0 is 1")
        else:
            if num == 1:
                return num
            else:
                return num*factorial_with_recursion(num-1) # calling same function within
    except:
        return 'Wrong Value Entered'
        # pass

Factorial function – using Recursion(calling)

num = int(input('Enter any positive number\n'))
# calling function from outside
print(f'Factorial of {num}! = {factorial_with_recursion(num)}')

Fibonacci Function – using Recursion

def fibonacci_with_recursion(num):
    if num <= 1:
        return num
    Else:
        return(fibonacci_with_recursion(num-1) + fibonacci_with_recursion(num-2))

num = int(input('Enter number for Fibonacci sequence\n'))

if num <= 0:
   print("Please enter a positive integer")
else:
    print("Fibonacci sequence:")
    for i in range(num):
        print(fibonacci_with_recursion(i),end=',')