Python entry function

Source: Internet
Author: User
Tags sin
To invoke a function, you need to know the name and parameters of the function, such as an absolute function abs, which receives a parameter.

Documents can be viewed directly from the official Python website:
Http://docs.python.org/2/library/functions.html#abs

You can also view the Help information for the ABS function on the interactive command line by helping (ABS).

Call the ABS function:

>>> ABS (100)
100
>>> ABS (-20)
20
>>> ABS (12.34)
12.34

When calling a function, if the number of arguments passed in is incorrect, the TypeError error is reported, and Python will explicitly tell you that ABS () has only 1 parameters, but gives two:

>>> ABS (1, 2)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Typeerror:abs () takes exactly one argument (2 given)

If the number of arguments passed in is correct, but the parameter type cannot be accepted by the function, the TypeError error is reported, and an error message is given: STR is the wrong parameter type:

>>> ABS (' a ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
Typeerror:bad operand type for abs (): ' Str '

The comparison function cmp (x, y) requires two parameters, if x<y, returns 1, if x==y, returns 0, if X>y, returns 1:

>>> CMP (1, 2)
-1
>>> CMP (2, 1)
1
>>> CMP (3, 3)
0

Python's built-in common functions also include data type conversion functions, such as the Int () function, which converts other data types to integers:

>>> Int (' 123 ')
123
>>> Int (12.34)
12

The STR () function converts other types to str:

>>> STR (123)
' 123 '
>>> Str (1.23)
' 1.23 '

To write a function:

In Python, define a function to use the DEF statement, write down the function name, parentheses, the arguments in parentheses, and the colon: and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

Let's take the example of a custom my_abs function that asks for an absolute value:

def my_abs (x):
If x >= 0:
return x Else:
Return-x

Note that when the statement inside the function body executes, once it executes to return, the function finishes and returns the result. Therefore, it is possible to implement very complex logic within a function through conditional judgments and loops.

If there is no return statement, the result is returned after the function is executed, except that the result is none.

Return none can be shortened to return.

Return multiple values:

Can a function return multiple values? The answer is yes.

For example, in the game often need to move from one point to another point, give the coordinates, displacements and angles, you can calculate the new coordinates:

# The Math package provides the sin () and cos () functions, which we first refer to with import:

Import Math
def move (x, y, step, angle):
NX = x + step * Math.Cos (angle)
NY = y-step * Math.sin (angle)
Return NX, NY

So we can get the return value at the same time:

>>> x, y = Move (+, +, MATH.PI/6)
>>> print x, y
151.961524227 70.0

But this is just an illusion, and the Python function returns a single value:

>>> r = Move (+, +, MATH.PI/6)
>>> Print R
(151.96152422706632, 70.0)

Prints the returned result with print, the original return value is a tuple!

However, in syntax, the return of a tuple can omit parentheses, and multiple variables can receive a tuple at the same time, by the location of the corresponding value, so the Python function returns a multi-value is actually returned a tuple, but it is more convenient to write.

Recursive functions:

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

For example, let's calculate factorial n! = 1 * 2 * 3 * ... * n, denoted by the function fact (n), you can see:

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

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.

The use of recursive functions requires careful prevention of stack overflow. In the computer, the function call is implemented through a stack (stack) of this data structure, each time into a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls that can cause the stack to overflow. You can try to calculate fact (10000).

The definition of a function move (n, a, B, c) is to move n discs from A through B to C.

Reference code:

def move (n, a, B, c):
If n ==1:
Print a, '--', C
Return
Move (N-1, A, C, b)
Print a, '--', C
Move (n-1, B, A, c)
Move (4, ' A ', ' B ', ' C ')

The method of solving recursive call stack overflow is optimized by tail recursion, in fact, the effect of tail recursion and loop is the same, so it is possible to think of the loop as a special tail recursive function.

Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursive itself, regardless of the number of calls, only occupy a stack frame, there is no stack overflow situation.

The fact (n) function above introduces a multiplication expression due to return n * fact (n-1), so it is not a tail-recursive. To change to a tail recursion, more code is needed, mainly to pass the product of each step into the recursive function:

def fact (N):
Return Fact_iter (n, 1) def fact_iter (num, product):
if num = = 1:return product return fact_iter (num-1, num * product)

As you can see, return fact_iter (num-1, num * product) only returns the Recursive function itself, and num-1 and num * Product are evaluated before the function call, without affecting the function call.

The call to fact (5) corresponding to Fact_iter (5, 1) is as follows:

===> Fact_iter (5, 1)
===> Fact_iter (4, 5)
===> Fact_iter (3, 20)
===> Fact_iter (2, 60)
===> Fact_iter (1, 120)
===> 120

At the end of a recursive call, if optimized, the stack does not grow, so no amount of calls will cause the stack to overflow.

Unfortunately, most programming languages are not optimized for tail recursion, and the Python interpreter is not optimized, so even changing the above fact (n) function to tail recursion can cause the stack to overflow.

Define default parameters:

When defining a function, you can also have default parameters.

For example, the python's own int () function, in fact, there are two parameters, we can both pass a parameter, and can pass two parameters:

>>> Int (' 123 ')
123
>>> Int (' 123 ', 8)
83

The second argument of the Int () function is the conversion, if not passed, the default is decimal (base=10), and if passed, use the passed in parameters.

As you can see, the function's default parameter is to simplify the call, and you just need to pass in the necessary parameters. However, when needed, additional parameters can be passed in to override the default parameter values.

Let's define a function that calculates the n-th square of x:

def power (x, N):
s = 1
While n > 0:
n = n-1
s = S * x
return s

Assuming the maximum number of squares is calculated, we can set the default value of N to 2:

def power (x, n=2):
s = 1
While n > 0:
n = n-1
s = S * x
return s

In this way, you do not need to pass in two parameters to calculate the square:

>>> Power (5)
25

Because the parameters of the function match in order from left to right, the default parameters can only be defined after the required parameters:

# Ok:def Fn1 (A, b=1, c=2):
pass# error:def fn2 (a=1, B):
Pass

First define a function, pass in a list, add an end and return:

def add_end (l=[]):
L.append (' END ') return L

When you call normally, the result looks good:

>>> Add_end ([1, 2, 3]) [1, 2, 3, ' End ']>>> add_end ([' X ', ' y ', ' z ']) [' X ', ' y ', ' z ', ' End ']

When you use the default parameter call, the result is also right at the beginning:

>>> add_end () [' End ']

However, when you call Add_end () again, the result is incorrect:

>>> add_end () [' End ', ' End ']>>> add_end () [' End ', ' End ', ' end ']

Many beginners are puzzled, the default parameter is [], but the function seems to "remember" the last time the "END" after the list.

The reasons are explained as follows:

When the Python function is defined, the value of the default parameter L is computed, that is, [] because the default parameter, L, is also a variable, which points to the object [], each time the function is called, if the content of L is changed, the contents of the default parameter will change the next time the function definition is no longer [].

So, one thing to keep in mind when defining default parameters: The default parameter must point to the immutable object!

To modify the above example, we can use the none of the immutable object to achieve:

def add_end (L=none):
If L is None:
L = []
L.append (' END ') return L

Now, no matter how many times it is called, there is no problem:

>>> add_end () [' End ']>>> add_end () [' End ']

Why design an immutable object such as Str and none? Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. When we are writing a program, if we can design a constant object, we try to design it as an immutable object.

To define a mutable parameter:

If you want a function to accept any of the arguments, we can define a variable parameter:

DEF fn (*args):
Print args

There is an * number in front of the variable parameter, we can pass 0, one or more parameters to the variable parameter:

>>> fn ()
()
>>> fn (' a ')
(' A ',)
>>> fn (' A ', ' B ')
(' A ', ' B ')
>>> fn (' A ', ' B ', ' C ')
(' A ', ' B ', ' C ')

The Python interpreter assembles the passed set of parameters into a tuple and passes it to the mutable parameter, so it's good to think of the variable args as a tuple directly inside the function.

Keyword parameters:

Variable parameters allow you to pass in 0 or any of the parameters that are automatically assembled as a tuple when the function is called. The keyword parameter allows you to pass in 0 or any parameter with parameter names that are automatically assembled inside the function as a dict. Take a look at the example:

def person (name, age, **kw):
Print (' name: ', Name, ' Age: ', age, ' other: ', kw)

The function person accepts the keyword parameter kw, in addition to the required parameter name and age. When you call this function, you can pass in only the required parameters:

>>> person (' Michael ', 30)
Name:michael age:30 Other: {}

You can also pass in any number of keyword parameters:

>>> person (' Bob ', city= ' Beijing ')
Name:bob age:35 Other: {"City": ' Beijing '}>>> person (' Adam ', ' a ', ' gender= ' M ', job= ' Engineer ')
Name:adam age:45 Other: {' Gender ': ' M ', ' job ': ' Engineer '}

What is the keyword argument for? It can extend the functionality of the function. For example, in the person function, we are guaranteed to receive both the name and the age parameters, but we can receive them if the caller is willing to provide more arguments. Imagine you are doing a user registration function, in addition to the user name and age is required, the other is optional, using the keyword parameters to define this function can meet the requirements of registration.

Named keyword parameters:

For the keyword argument, the caller of the function can pass in any unrestricted keyword argument. As to exactly what is passed in, it needs to be checked inside the function via KW.

Still taking the person () function as an example, we want to check if there are city and job parameters:

def person (name, age, **kw):
If ' City ' in kw: # There are city parameters
Pass
If ' job ' in kw: # There are job parameters
Pass
Print (' name: ', Name, ' Age: ', age, ' other: ', kw)

However, the caller can still pass in the Unrestricted keyword parameter:

>>> person (' Jack ', city= ' Beijing ', addr= ' Chaoyang ', zipcode=123456)

If you want to restrict the name of the keyword argument, you can use the named keyword argument, for example, to receive only city and job as the keyword parameter. The functions defined in this way are as follows:

def person (name, age, *, City, Job):
Print (name, age, city, job)

Unlike the keyword argument **kw, a named keyword parameter requires a special delimiter *,* the parameters that follow are treated as named keyword parameters.

The method is called as follows:

>>> person (' Jack ', city= ' Beijing ', job= ' Engineer ')
Jack Beijing Engineer

The named keyword argument must pass in the parameter name, which differs from the positional parameter. If the parameter name is not passed in, the call will error:

>>> person (' Jack ', ' Beijing ', ' Engineer ')
Traceback (most recent):
File "<stdin>", line 1, in <module>typeerror:person () takes 2 positional arguments but 4 were given

Because the call is missing the parameter name City and the Job,python interpreter treats all 4 parameters as positional parameters, the person () function accepts only 2 positional arguments.

A named keyword parameter can have a default value, which simplifies the invocation:

def person (name, age, *, city= ' Beijing ', job):
Print (name, age, city, job)

Because the named keyword parameter city has a default value, the city parameter is not passed in when called:

>>> person (' Jack ', job= ' Engineer ')
Jack Beijing Engineer

When using a named keyword parameter, pay special attention to that * is not a parameter, but a special delimiter. If the missing *,python interpreter will not recognize the positional parameter and the named keyword parameter:

def person (name, age, City, job):
# missing *,city and job are treated as positional parameters
Pass

Parameter combinations:

Define functions in Python, which can be combined using required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, except that mutable parameters cannot be mixed with named keyword parameters. Note, however, that the order of the parameter definitions must be: required, default, variable/named keyword, and keyword parameters.

For example, define a function that contains several of the above parameters:

Def f1 (A, B, c=0, *args, **kw):
Print (' A = ', A, ' B = ', B, ' C = ', C, ' args = ', args, ' kw = ', kw) def F2 (A, B, c=0, *, D, **kw):
Print (' A = ', A, ' B = ', B, ' C = ', C, ' d = ', D, ' kw = ', kw)

At the time of the function call, the Python interpreter automatically passes the corresponding parameters according to the parameter location and argument name.

>>> F1 (1, 2)
A = 1 b = 2 c = 0 args = () kw = {}>>> F1 (1, 2, c=3)
A = 1 b = 2 c = 3 args = () kw = {}>>> F1 (1, 2, 3, ' A ', ' B ')
A = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {}>>> F1 (1, 2, 3, ' A ', ' B ', x=99)
A = 1 b = 2 c = 3 args = (' A ', ' b ') kw = {' x ': 99}>>> F2 (1, 2, d=99, Ext=none)
A = 1 b = 2 c = 0 d = HP = {' ext ': None}

The most amazing thing is that through a tuple and dict, you can also call the above function:

>>> args = (1, 2, 3, 4) >>> kw = {' d ':}>>>, ' x ': ' # ' F1 (*args, **kw)
A = 1 b = 2 c = 3 args = (4,) kw = {' d ':, ' x ': ' # '}>>> args = (1, 2, 3) >>> kw = {' d ': ", ' X ': ' # '}&G t;>> F2 (*args, **kw)
A = 1 b = 2 c = 3 d = x kw = {' × ': ' # '}

So, for any function, it can be called by the form of a func (*args, **kw), regardless of how its arguments are defined.

Summary

Python's functions have a very flexible parameter pattern, which allows for simple invocation and very complex parameters to be passed.

Default parameters must be used immutable objects, if it is a mutable object, the program will run with a logic error!

Be aware of the syntax for defining mutable parameters and keyword parameters:

*args is a variable parameter, and args receives a tuple;

**KW is the keyword parameter, and kw receives a dict.

And how to pass in the syntax for variable and keyword arguments when calling a function:

Variable parameters can be passed directly: Func (1, 2, 3), or the list or tuple can be assembled first, and then passed through *args: Func (* (1, 2, 3));

Keyword parameters can be directly passed in: Func (A=1, b=2), can be assembled dict, and then passed through **kw: func (**{' a ': 1, ' B ': 2}).

Using *args and **kw is a Python idiom, but it can also be used with other parameter names, but it's best to use idioms.

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 a named keyword parameter do not forget to write the delimiter *, otherwise the definition will be the positional parameter.

  • 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.