Python recursive functions

Source: Internet
Author: User
A function is like a box that packs some related functionality into a function for invocation. Other functions can be called inside the function, or the function itself can be called.
If a function calls the function itself internally, then this is the recursive function.
Let's give a simple example.
In mathematics we know the factorial of 100, 100!=1009998...321.
Break it apart, 100!=10099!,99!=9998!,98!=98*97!...
Then we define a function to calculate the factorial:

def fact (N):    return N*fact (n-1)

The above function appears to be a number that multiplies by 1 of its small number, but does not stop. So we have to transform the above function so that it can stop when the n=1 is done.

def fact (n):    if n==0:        return 1    else:        return n*fact (n-1)

Recursive functions can also be implemented in a circular manner. But recursive function logic is relatively simple. However, when using recursive functions, it is important to guard against excessive recursive function calls resulting in stack overflow.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.