In a program, a function can invoke another function, which in turn might call yet another function. Additionally, a function has the capability to call itself. Such a function is referred to as a recursive function. For instance, consider the function illustrated in the following program.
Bad Recursion Example
# This program has a recursive function. # NOTE: This program causes infinite recursion def main(): print_message() def print_message(): print('Hi. Do you know what a recursive function is?') print_message() # Call the main function. if __name__ == '__main__': main() |
The output will be:
Hi. Do you know what a recursive function is? Hi. Do you know what a recursive function is? Hi. Do you know what a recursive function is? … will be repeated infinitely. |
In the above example, the print_message function outputs the string 'Hi. Do you know what a recursive function is?' and then invokes itself again and again. There is no mechanism to terminate the recursive calls. This function acts like an infinite loop because there is no code to halt its repetition. If you execute this program, you will need to press Ctrl+C on the keyboard to stop its execution.
Similar to a loop, a recursive function needs a mechanism to control the number of times it executes. The following code is a revised version of the print_message function. In this version, the print_message function takes an argument that determines how many times the message should be displayed.
Revised Version:
# This program demonstrates a simple recursive function to print a message a specified number of times. def main(): times = 4 # Number of times to print the message print_message(times) def print_message(times): if times <= 0: # Base case: When times is 0 or less, stop the recursion return else: print('Hi. Do you know what a recursive function is?') print_message(times - 1) # Recursive case: Call the function with times - 1 # Call the main function. if __name__ == '__main__': main() |
Explanation
- Main Function: The main function initializes the number of times the message should be printed and calls the print_message function with that number.
- Print Message Function:
- Base Case: When times is 0 or less, the function stops calling itself, which prevents infinite recursion.
- Recursive Case: The function prints the message and then calls itself with times - 1, reducing the number of remaining prints by one each time.