PYTHON11: Functions

Source: Internet
Author: User
Tags vars

When you need to write a large program, you may want to write a piece of code for other places to call, or to extract the same logic from the program, then you need to use the function. But functions not only provide these functions, but also help us to understand the code more easily by using functions.

Defining functions

The following code defines a function fib, which is used to calculate the Fibonacci sequence:

>>> def fib (n):        
The first is the keyword Def, followed by a function name and a list of parameters. Starting from the next line is the body of the function and must be indented.
The first line of the function can be a descriptive string, optionally, if any, to be stored as part of the function as a document string. There are tools that can automatically generate online or printed documents using a document string, or you can access them in the following ways:

>>> fib.__doc__ ' Print a Fibonacci series up to N. '
Or use the Help function:

>>> Help (FIB) Help on Function fib in module __MAIN__:FIB (n)    Print a Fibonacci series up to N.
The function can return a value using return, for example, to return a result sequence for the above fib function:

>>> def fib2 (n): "" "Return a list containing the Fibonacci series up to N." " result = []a, b = 0, 1while a < N:result.append (a) A, B = B, a+breturn result>>> F100 = fib2 (+) >>> F 100[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
If the function does not have a return statement, none is returned, such as:

>>> F100 = fib (+) 0 1 1 2 3 5 8 All-in-all >>> print (F100) None
More features of the functions in Python are described below.

Specifying a default value for a parameter

It is useful to specify a default value for a function parameter so that you can specify fewer parameters when calling the function, for example:

>>> def ask_ok (prompt, retries=4, complaint= ' Yes or No, please! '): While True:ok = input (prompt) If OK in (' Y ', ' ye ' Yes '): Return trueif OK in (' n ', ' No ', ' nop ', ' Nope '): return falseretries = retries-1if Retries < 0:raise OSError ( ' Uncooperative user ') print (complaint)
You can call this function in the following way:
1) specify only mandatory parameters:

>>> Ask_ok (' Does really want to quit? ') Do your really want to quit?ytrue
2) give one of the optional parameters:

>>> Ask_ok (' OK to overwrite the file? ', 2) OK to overwrite the File?nfalse
3) Give all the parameters:

>>> Ask_ok (' OK to overwrite the file? ', 2, ' Come on, only yes or no! ') OK to overwrite the File?nfalse
It is important to note that the default value of the function is determined at the moment of definition, for example:

>>> i = 5>>> def f (arg=i):p rint (arg) >>> i = 6>>> f () 5
Because the value of I is 5 when I define F, the call F () always prints 5.

Warning: The default value is only assigned once, but when the default value is a Mutable object (such as a list, dictionary, or an instance of a mutable class), there may be a problem, as shown in the following example, to accumulate the incoming values together:

>>> def f (A, l=[]): L.append (a) return l>>> print (f (1)) [1]>>> print (f (2)) [1, 2]>>> Print (f (3)) [1, 2, 3]
If you don't want to share the default values among multiple calls, you can do this:

>>> def f (A, L=none): If L is none:l = []l.append (a) return L

Keyword parameters

The function can be called using the keyword argument in the form: Kwarg=value. Here is an example:

>>> def parrot (voltage, state= ' a stiff ', action= ' voom ', type= ' Norwegian Blue '):p rint ("--this parrot wouldn ' t", Action, end= ') print ("If you put", voltage, "volts through it.") Print ("--lovely plumage, the", type) print ("--It's", State, "!")
Parrot specifies a mandatory parameter and 3 optional parameters. Parrot can be called using the following form:

Parrot (Parrot) (voltage=1000) Parrot (voltage=1000000, action= ' Vooooom ') Parrot (action= ' vooooom ', voltage= 1000000) Parrot (' A million ', ' bereft of life ', ' Jump ') parrot (' A-thousand ', state= ' pushing up ' daisies ')
Note the following method of invocation is not valid:

Parrot () Parrot (voltage=5.0, ' dead ') Parrot (voltage=220 ' John parrot ')

Variable length parameters

The function supports variable length parameters, and incoming parameters are packaged as a tuple, and 0 or more parameters can be supplied before a variable parameter.

>>> def write_multiple_items (file, separator, *args): File.write (Separator.join (args))
*args indicates that any parameter can be entered. Typically, mutable parameters are placed at the end of the parameter list, because they will include all subsequent input parameters. The parameters following any mutable parameter must be used in the form of a keyword parameter. Let's look at a specific example:

>>> def concat (*args, sep= "/"):    return Sep.join (args) >>> concat ("Earth", "Mars", "Venus") ' Earth /mars/venus ' >>> concat ("Earth", "Mars", "Venus", sep= ".") ' Earth.mars.venus '
In addition to the ' * ', Python also supports ' * * '. ' * * ' indicates that the passed in parameter is a dictionary, see the following example:

>>> def print_params (**params):p rint (params) >>> print_params (x=1,y=2,z=3) {' Z ': 3, ' X ': 1, ' Y ': 2}
In this way, the params is printed out as a dictionary. Here is a comprehensive example:

>>> def cheeseshop (Kind, *arguments, **keywords):p rint ("--Do you have any", kind, "?") Print ("---I ' m Sorry, we ' re all out of", kind) to Arg in Arguments:print (ARG) print ("-" * max) keys = sorted (Keywords.keys ()) F or kw in Keys:print (kw, ":", keywords[kw]) >>> cheeseshop ("Limburger", "it ' s very runny, sir.",           "it's really V ery, VERY runny, sir. ",           shopkeeper=" Michael Palin ",           client=" John Cleese ",           sketch=" Cheese Shop Sketch ")-- Do Limburger?--I ' m sorry, and we ' re all out of Limburgerit ' s very runny, sir. It ' s really very, very runny, sir.----------------------------------------Client:john Cleeseshopkeeper:michael Palins Ketch:cheese Shop Sketch

Unpacking lists and tuples

The incoming parameters have been packaged as a tuple and dictionary using ' * ' and ' * * ', but if the parameter is already a list or tuple, how can it be passed as a parameter? You can use ' * ' and ' * * ' to unpack it. Look at the following example:

>>> args = [3, 6]>>> list (range (*args)) [3, 4, 5]
In the same way, a dictionary can be used as a keyword parameter by using the ' * * ' operator:

>>> def parrot (voltage, state= ' a stiff ', action= ' voom '):p rint ("--this parrot wouldn ' t", action, end= ') print (" If you put ", voltage," volts through it. ", end=") print ("E-S", State, "!")  >>> d = {"Voltage": "Four Million", "state": "Bleedin ' demised", "Action": "Voom"}>>> Parrot (**d)--This Parrot Wouldn ' t voom if you put a four million volts through it. E ' s bleedin ' demised!

Lambda expression

You can use the Lambda keyword to create small, anonymous functions, such as the following function, which returns two parameters and:

Lambda A, b:a+b
Lambda functions are syntactically limited to single-expression, and semantically they are only the simplified syntax of the usual function definitions. Like a nested function definition, a lambda function reference contains a variable in scope.

>>> def make_incrementor (n): return lambda x:x + n>>> f = make_incrementor ($) >>> F (0) 42>&G T;> F (1) 43
The above is the use of a lambda expression to return a function, here is another example, passing a small function as a parameter:

>>> pairs = [(1, ' One '), (2, ' One '), (3, ' three '), (4, ' four ')]>>> Pairs.sort (Key=lambda pair:pair[1]) & Gt;>> pairs[(4, ' Four '), (1, ' One '), (3, ' three '), (2, ' both ')]

function comment

Function comments are optional, including arbitrary information about user-defined functions. Both python itself and the standard library do not use function annotations, which show the syntax of function annotations.
Comments are stored in the __annotations__ property of the function, and parameter comments are followed by an expression by a colon defined by the argument, and the return comment is defined by syntax---. Here is an example:

>>> def f (ham:42, eggs:int = ' spam '), "nothing to see here":p rint ("Annotations:", f.__annotations__) print ( "Arguments:", ham, eggs) >>> f (' wonderful ') Annotations: {' return ': ' Nothing to see here ', ' Ham ': ", ' eggs ': <c Lass ' int ' >}arguments:wonderful spam

Scope

Variables in Python are placed in a dictionary, stored as "name-by-value". The built-in VARs function can return this dictionary:

>>> x = 1>>> scope = VARs () >>> scope[' x ']1
This dictionary is called a namespace or scope. Each function call creates a new scope, and the variable inside the function is called a local variable, and the parameter is similar to a local variable.
Python provides a way to access global variables in a function, you can use the GLOBALS function to get the value of a global variable, and the close relative of the function is VARs, for example:

>>> def combine (parameter):p rint (parameter + globals () [' parameter ']) >>> parameter = ' Berry ' >> > Combine (' shrub ') shrubberry
You can also use a method that binds global variables:

>>> x = 1>>> def change_global (): Global xx = x + 1>>> change_global () >>> x2
But this can lead to confusion, and it is recommended that you try not to do so.

PYTHON11: Functions

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.