|
||||||||
Recursion in Python - Python Automation and Machine Learning for ICs - - An Online Book - |
||||||||
| Python Automation and Machine Learning for ICs http://www.globalsino.com/ICs/ | ||||||||
| Chapter/Index: Introduction | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | Appendix | ||||||||
================================================================================= Recursion is a programming concept where a function calls itself in its own definition. In Python, a recursive function is a function that, in order to accomplish its task, makes one or more calls to itself with modified arguments. The process of a function calling itself is known as a recursive call. An example of recursive functions in Python is to calculate the factorial of a number (code): Output:
In the example above, the factorial function calculates the factorial of a number n by recursively calling itself with a modified argument (n - 1). The base case (if n == 0 or n == 1) is crucial to prevent the recursion from continuing indefinitely and causing a stack overflow. In this case, when n is 0 or 1, the function returns 1, serving as the termination condition. Recursion can be a powerful and elegant technique, but it's important to use it judiciously and ensure that the base case(s) are well-defined to avoid infinite recursion. Improperly handled recursion can lead to a stack overflow error. ============================================
|
||||||||
| ================================================================================= | ||||||||
|
|
||||||||