Recursion
In Python, just like many other programming languages, a defined function can call itself. This is known as recursion. A recursive pattern has two important components. The first is the termination condition, which defines when to terminate the recursion. In the absence of this or if it is erroneous (never meets the termination criteria), the function will call itself an infinite number of times. This is called infinite recursion. The other part of the recursion pattern is recursive calls. There can be one or more of these. The following program demonstrates simple recursion:
def print_message(string, count): if (count > 0): print(string) print_message(string, count - 1) print_message("Hello, World!", 5)
In the preceding program, we use recursion in place of a for
or while
loop to print a message repetitively.
Let’s write a program...