Python Basic 4 functions

Source: Internet
Author: User

basic syntax and characteristics of functionswhat is a function?

Defined:

A function is to encapsulate a set of statements by a name (function name), and to execute the function, simply call the name of its functions.

Characteristics:

Reduce duplicate code

To make the program extensible

Make the program easy to maintain

def Sayhi ():    #  function name    print('Hi, I'm jack!'  )sayhi ()    #  Call function

Functions can also take parameters

def Test (x, y):     Print (x, y) test (.)

function parameters and local variables

Formal parameters:

A variable allocates a memory unit only when it is called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. The parameter variable can no longer be used after the function call finishes returning the keynote function.

Actual parameters:

Can be constants, variables, expressions, functions, and so on, regardless of the amount of the arguments, they must have a definite value when making a function call to pass these values to the parameter. Therefore, the parameter should be determined by the method of assignment, input and so on beforehand.

def Test (x, y):     #  x, y for formal parameter           Print(x + y)    Test (1, 2)    #  1, 2 is the actual parameter

Default parameters:

def Test (x, Y, z=3):    #  z is the default parameter    print(x + y + z)    Test (1, 2)      # in a function call, you can not give a value of Z, and if not, the value of the parameter is 3

Keyword parameters:

Under normal circumstances, to pass parameters to the function in order, do not want to order the key parameters can be used, just specify the parameter name, but remember a requirement is that the key parameters must be placed after the position parameter.

def Test (x, Y, z):     Print (x + y + z) Test (1, z=3, y=10)    # when the test function is called, the position parameter 1 is assigned to x and the z and Y are passed in the function as the keyword argument.

Non-fixed parameters:

If your function is undefined in terms of how many parameters the user wants to pass in, you can use a non-fixed parameter, and *args will change the number of arguments into a tuple form.

def Test (x, y, *args):    print('x, y, *args', x, y, args) Test (1, 2, 3, 4)>>> x, y, *args 1 2 (3, 4)

You can also have a **kwargs,*kwargs that turns multiple incoming parameters into a dict form.

def Test (x, y, *args, * *Kwargs)    :print('x, y, *args, **kwargs'  , x, y, args, Kwargs) test (1, 2, 3, 4, a=5, b=6, c=7)>>>x, y, *args, **kwargs 1 2 (3, 4) { c10> 'C'a''b': 6}

Local variables

' Jack ' def Test (name):     ' Tom '    Print (', name ') test ('name')

The function checks the name variable from itself to invoke the

Global variables and local variables

A variable defined in a subroutine is called a local variable, and a variable defined at the beginning of the program is called a global variable. The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable. When a global variable has the same name as a local variable:Local variables work in sub-programs that define local variables, and global variables work elsewhere.  return valueTo get the result of the function execution, you can return the result using the return statement

Attention:

The function will stop executing and return the result as soon as it encounters a return statement, or it can be understood that the return statement represents the end of the function.

If return is not specified in the function, the return value of this function is None

nested Functions
' Tom ' def change_name1 ():     ' Tom1 '    def change_name2 ():         ' Tom2 '        Print (name)    change_name2 ()    print(name) change_name1 ()print( Name

Recursive

Recursive properties:

Must have a definite end condition

Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion

Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering 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, which can cause the stack to overflow.

def Calc (n):     Print (n)     if int (N/2) = = 0        :return  n    print('----  ')    return calc (int (n/2)) Calc (10)

Anonymous Functions

An anonymous function is one that does not require an explicit function to be specified

def Calc (n):     return nprint(calc)#  anonymous function lambda n:n* N Print (Calc (10))

Higher order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

def Add (x, Y, f):     return f (x) += Add ( -3, 4, ABS)print(res)

iterators, generators, adornersiterators

Objects that can be used for loops are iterative objects
Any object that can be used for the next () function is an iterator type that represents a sequence of lazy computations
The collection data type is an iterative object, but not an iterator, and an iterator object can be obtained through the ITER () function
Python's for loop is essentially implemented by calling the next () function continuously.

Import TimedefConsumer (name):Print("%s ready to eat buns! "%name) whileTrue:baozi=yield        Print("Bun [%s] came, eaten by [%s]"%(baozi,name))defproducer (): C1= Consumer ("Jack") C2= Consumer ("Tom") C1.__next__() c2.__next__()     forIinchRange (1,11): Time.sleep (1)        Print("1 buns, divided into two parts! ") c1.send (i) c2.send (i) producer ()
Generator
#List-generatedList1 = [i*2 forIinchRange (1,11)]list= (x*2 forXinchRange (1,1000000))#function Builderdeffib (max): N,a,b= 0,0,1 whileN <Max:#print (b)        yieldb A, a= b,a+B N= n + 1#Print message when return is abnormal    return " Done"g= FIB (10) whileTrue:Try: x=Next (g)Print("g:", X)exceptstopiteration as E:Print("Generator return value:", E.value) Break
Decorative Device

is itself a function, (decorating other functions) is to add additional functionality to other functions

Principle:

Cannot modify the source code of the decorated function

Cannot modify the calling method of the decorated function

Implement the Adorner Knowledge Reserve:

function is "variable"

Higher order functions

Nested functions

Higher order function + nested function = "Adorner"

defLogging (func):defWarpper (*args,**Kwargs): Func (*args,**Kwargs)Print("Logging ...")    returnWarpper @loggingdeftest1 (name,age):Print("func in%s,%s"%(name,age)) @loggingdeftest2 (name,age):Print("func in%s,%s"% (Name,age))

Python Basic 4 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.