function parameters and recursive parameters of Python

Source: Internet
Author: User
Tags function definition

Position parameters
def power(x):    return x*x;    
Default parameters

When a function is defined, it is given the default value of the parameter, and it is not necessary to pass the duplicate parameter value multiple times when calling the function.
Define a multiple output for the same age period and the name and gender of the student in the same city.

def info(name,gender,age=20,city=‘sichuan‘):    print(‘name:‘, name)    print(‘gender:‘, gender)    print(‘age‘,age)    print(‘city‘,city)info("xiaoqian","nv")info("xiangj",‘nan‘)

As can be seen from the above, the default parameters can simplify the invocation of functions, when setting default parameters, there are a few things to note:
The first is the required parameter before the default parameter is in the back.
The second is how to set the default parameters.
However, the default parameters are good, but they also have pits: when defining default parameters, the default parameter must be an immutable object.

Variable parameters (*)
Variable parameter is the number of parameters passed in is variable, can be 1, 2 or more, or even 0
def calc(*numbers):    sum = 0;    for n in numbers:        sum = sum + n;    return sum;calc();calc(1,2,3);

What if you have a list or a tuple and you want to invoke a mutable parameter?
Python allows you to precede the list or tuple with * to pass to the function.

num  = [1,2,3];cal(*num);

Variable parameters allow incoming 0,1,n parameters, which are automatically assembled into a tuple when called. The keyword parameter allows you to pass in 0 or one parameter with parameter names, which are automatically assembled into a dict inside the function.

Keyword parameters (* *)
def person(name,age,**kw):    print(‘name‘,name,‘age‘,age,‘other‘,kw)person(‘tom‘,20);person(‘tom1‘,10,city="beijinh");person(‘tom2‘,30,gender="m",city="beijing");

The above gender and city parameters can also be assembled into a dict and then passed to the function

extra = {‘city‘:‘beijing‘,‘job‘:‘engin‘};person(‘tom11‘,100,city=extra[‘city‘],job=extra[‘job‘]);person("tom11",100,**extra);//注意这里kw获得的是extra的一份拷贝,对kw的改动不会影响到函数外的extra
Named keyword parameter (* special delimiter)
A function can accept an unrestricted keyword argument by calling the keyword parameter.
But sometimes you need to limit the number of keyword parameters, so you need to use the named keyword parameter
def person(name,age,*,city,job):    print(name,age,city,job);    //命名关键字参数需要一个特殊分隔符*,*后面的参数被视为命名关键字参数。person("jackl",14,city="beijing",job="gee");//命名关键字参数必须传入参数名,这和位置参数不同,如果没有传入参数名,调用就将报错

If there is already a mutable parameter in the function definition, then the named keyword argument does not need a special delimiter.

def person(name,age,*args,city,job):    print(name,age,args,city,job)

It is important to note that if you do not have a mutable parameter, you must add one as a special delimiter, otherwise Python will not recognize the positional and named keyword parameters.
Summarize:
There are 5 parameters in the Python function: required, default, variable, keyword, and named keyword. You can combine these several parameters. Note, however, that the order of the parameter definitions must be:
Required parameters, default parameters, mutable parameters, named keyword parameters, and keyword parameters.
Default parameters must be used with immutable objects
Args is a mutable parameter, and args accepts a tuple.
KW is the keyword parameter, and KW accepts a dict.
Variable parameters can be directly passed in: Func (+/-), or the list or tuple can be assembled, and then passed through args: func (())
The keyword parameter can either be passed directly to Func (a=1,b=2), the dict can be assembled first, and then the Func is
passed in by kw (**{' a ': 1, ' B ': 2})
The named keyword parameter is used to limit the name of the parameter that the caller can pass in, as well as providing a default value.
Define named key cashier number Sue, in the absence of variable parameters, do not forget to write special delimiter *, otherwise the definition will be positional parameters.

Recursive functions

The advantage of recursive functions is that they are simple in definition and clear in logic. But sometimes there is a stack overflow.
The method of resolving stack overflow is tail recursion. In fact, the effect of tail recursion and circulation is the same, it is possible to think of loops as a special kind of tail recursive function.
Tail recursion: When the function returns, it calls itself, and the return statement cannot contain an expression.

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

The return in the above contains the expression, which is not a tail-recursive.

def fact_item(num,product):    if num == 1:        return product    return fact_item(num-1,num*product)

Above this is the tail recursion, did the optimization, the stack does not grow, so how many times the call will not cause the stack overflow.
Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even if the above fact (n) function is changed to a tail recursion, it can cause the stack to overflow

function parameters and recursive parameters of Python

Related Article

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.