minte9
LearnRemember



Recursion

It is legal for a function to call itself (one of the most magical things a program can do).
 
# Recursion:
#
# A function can call himself

def countdown(n):
    if n <= 0:
        print ("Time!")
    else:
        print(n)
        countdown(n-1)

countdown(3)

# 3
# 2
# 1
# Time!

Flow

What happens if we call this function like this?
 
countdown executions begins with n=3 ...
since n is greater than 0 it outputs 3 ..
then it calls itself ...

    countdown executions begins with n=2 ...
    since n is greater than 0 it outputs 2 ..
    then it calls itself ...

        countdown executions begins with n=1 ...
        since n is greater than 0 it outputs 1 ..
        then it calls itself ...

            countdown executions begins with n=0 ...
            since n is not greater than 0 it outputs Time! ..
            then returns ...

        the countdown that got n=1 returns

    the countdown that got n=2 returns

the countdown that got n=3 returns

After that we are back in the __main__

Repeat

As another example, we can print a string n times.
 
# It is easier to write a for loop ...
# but there are times when we need recursion.

def repeat(s, n):
    if n <=0 :
        return
    print(s)
    repeat(s, n-1)

repeat('abc', 3)
    # abc
    # abc
    # abc



  Last update: 205 days ago