Learn practical skills, build real-world projects, and advance your career
# Program to print sum of first 5 natural numbers - Non Recursive Function
# 1+2+3+4+5 = 15

def sum_n(n):
    sum1 = 0
    for i in range(1,n+1):
        sum1 = sum1+i
    return sum1

print(sum_n(5))
15

Recursion

A function calling itself.

Note: There always has to be a boundary condition for recursion, else it will go into an infinite loop.

def abc():
    print("Hi from abc")
    abc()
    
abc()
# Program to print sum of first 5 natural numbers - Recursive Function
# 1+2+3+4+5 = 15

def sum_n(n):
    if n==1:
        return n
    else:
        return n + sum_n(n-1)
    
num = int(input("Enter no: "))
print(sum_n(5))
Enter no: 5 15
What is good? Recursive or Non Recursive Function?

Non recursive functions are always preferred.

Why?
1. Use of additional data structure like stack consumes additional memory.

2. It also consumes additional time in pushing and popping values in and out of the stack.

3. Recursive functions are slow.