Python Learning routines-function parameters and recursion

Source: Internet
Author: User

First say recursion: Because the principle is simple, but to use flexibly, it is very difficult.

The principle of recursion is to call the function itself within the function to achieve the purpose of the loop,

such as a factorial function def fn (n):

If n==1:

return n;

else:

RETURN fn (n-1) *n;

There is also the idea of a tail recursion, because recursion is very easy to stack overflow, so the left function itself should not appear in the return value.

The above factorial can be converted to DEF fn (n,product):

If n==1:

return product;

else:

RETURN fn (n-1,n*product);

def use (n):

RETURN fn (n,1);

Again, the parameters of the function:

The parameters of the function are divided into 5 types, positional parameters, default parameters, variable parameters, keyword parameters, and specific keyword parameters.

In defining a function, these five types of parameters must be sequential, but some of them can be missing

Positional parameters are general parameters, Def F (A, B):

Pass

Default parameter: def f (a= "a"):

Pass

Can be called directly f (), or F ("B");

A variable parameter is one that can be used when the number of arguments is indeterminate, for example: Def f (*PRA):

Pass

The keyword parameter is def f (**kw):

Pass

Called when F (a= "a", b= "B");

The variable parameter is encapsulated as a tuple, and the keyword parameter encapsulates a dic;

The specific keyword parameter is def f (*,a= "A", b):

Pass

As can be seen from the definition, the parameter a can be called by default, B cannot be f ("B");

              

Python Learning routines-function parameters and recursion

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.