Python recursive functions and Examples
Python recursive functions
If a function body calls itself directly or indirectly, this function is called a recursive function. that is to say, during the execution of the recursive function body, it may return to call the function again. in python, recursive functions do not need any special syntax, but they need to make some effort to understand and create them.
Let's start with a simple example: Write a function to calculate the sum of all numbers in a natural number. when designing recursive functions, we will look for ways to break down the problem into simple ones. in this question, the operator % and // can be used to divide a number into two parts: the inner bit and the inner digit.
The sum of digits 18117 is: 1 + 8 + 1 + 1 + 7 = 18. in this way, we can split this number. divide the number into 7 digits and 1 + 8 + 1 + 1 = 11. this method provides an algorithm for us to calculate the sum of digits of n by adding the sum of digits n % 10 and n // 10. this method has a special situation: If a number has only one digit, the sum of its numbers is itself. this algorithm can be implemented using recursive functions.
Def sum_digit (n): "" return the sum of the digit of positive integer n. "if n <10: return n else: last = n % 10 all_but_last = n // 10 return sum_digit (all_but_last) + last
The sum_digit function is completely and correctly defined, even if the sum_digit function is called in its own function body.
In this way, the question of finding the sum of numbers is divided into two parts: finding the sum of the digits excluding the percentile, and then adding the percentile. both steps are simpler than the original ones. this function is recursive, because the problem in the first step is of the same type as the original problem. that is to say, sum_digit is indeed a function that we need to calculate the sum of natural numbers.
We can understand how this recursive function is successfully applied using the computing environment model. It does not require any new specifications.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!