Python Recursion Example

Below code demonstrates recursion in Python programming. Recursion occurs when a method calls itself.

#Python recursion
#Recursion in Python is when a program calls itself.

def countdown_timer(x):
    if x == 0:
        print("Stop")
        return
    else:
        print(x, "...")
        countdown_timer(x - 1)

countdown_timer(10)
------------------------------------------------------------
#Output
10 ...
9 ...
8 ...
7 ...
6 ...
5 ...
4 ...
3 ...
2 ...
1 ...
Stop



When we add a print method at the else statement then let's see what happens.


#Python recursion
#Recursion in Python is when a program calls itself.

def countdown_timer(x):
    if x == 0:
        print("Stop")
        return
    else:
        print(x, "...")
        countdown_timer(x - 1)
        print("Do something!")

countdown_timer(10)

----------------------------------------------------------
#Output
10 ...
9 ...
8 ...
7 ...
6 ...
5 ...
4 ...
3 ...
2 ...
1 ...
Stop
Do something!
Do something!
Do something!
Do something!
Do something!
Do something!
Do something!
Do something!
Do something!
Do something!


Comments

Popular posts from this blog

Wordpress - Upload multiple files using wp_handle_upload

Python Tkinter example

How to write to a file in Kotlin