Python: recursive function

Source: Internet
Author: User

Inside the function we can call other functions such as:

def say (Great):     return Great def Person (name):     Print (Say ("Hello"), name) person (" Sandichicks ")

Print as follows:

>>> Hello Sandichicks

But if we call ourselves, this function is a recursive function

For example, let's calculate factorial n! = 1 x 2 x 3 x ... x n (for example, the factorial of 5:5*4*3*2*1) is indicated by the function fact (n), which shows:

Fact (n) = n! = 1x 2 x 3 x ..... x (n-1) x n = (n-1)! X n = fact (n-1) * n

So, fact (n) can represent n * Fact (n-1), and only n = 1 o'clock requires special handling. (otherwise 1*fact (1-1) =0 no meaning)

So, fact (n) is written in a recursive way:

def fact (N):     if n = =1        :return 1    return N * Fact (N-1)

The above is a recursive function, we write it a function to facilitate our presentation of the results

Detail = input ("Factorial calculator: 99 reference Calculator Press any key to continue \ n")defFace (n):ifn = = 1:        return1returnn * Face (n-1) whileTrue:num= Int (Input ("Enter the number of factorial you want to find:"))    Print("the factorial result is:", Face (num))Print("---------------------")

So we can demonstrate the factorial calculator program we wrote!

If we calculate the fact (5), we can see the calculation process according to the function definition as follows:

===> fact(5)===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24===> 120


The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.

Python: recursive function

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.