Python Lesson Fourth----function

Source: Internet
Author: User
Tags chr closure function definition in degrees variable scope

Function

First, the function

A statement block consisting of several statements, a function name, a parameter list, which is the smallest unit of the organization's code.

function of functions

1, the most basic package of code, according to the function of organizing a piece of code. 2, in order to reuse, to reduce redundant code.

III. Classification of functions

1. Built-in function: Max (), reversed (). 2, library function: Math.ceil.

Definition function of DEF statement

def function name (argument list) function body (code block) [return value] The function name is the identifier, and the naming requirement is the same. A statement block indents four spaces. If there is no return statement in the function, implicitly returns a value of None. A parameter list in a definition is a formal parameter, just an expression, or a formal parameter.
2, call the function definition, just declare, will not execute, need to invoke the call plus the parentheses call when the argument is the actual parameter, is the value passed in, referred to as the argument

V. Definition of function, calling

def add (x, y): result = x+y return resultout = Add (4,5) print (out)
The function---->add, the result is returned by the return value, the return value can be received using the variable, the function is a callable object, callable (add) is a generic

Vi. function parameters

1, parameter invocation, the parameters to be passed in and the number of definitions to match (variable exception) 2, positional parameters: Def f (x, Y, z) Call: F (3,4,5), in order to pass in argument 3, key parameters: Def f (x, Y, z) Call: F (x=3,y=4,z=5), Use formal parameter names to pass in the arguments, the order does not matter 4, the argument: F (z=none,y=10,x=[1]), F ((1,), z=6,x=4.1), F (y=5,z=6,2) The last of these, positional parameters must be passed in before the keyword parameter

Seven, parameter default value

1, parameter default value: Def f (x=4,y=5): This time, x, Y has default value, the default can output 2, the parameters are very many times, do not need to output all parameters, there is a default value can be

Eight, variable parameters

1, the question: There are many number, summed up and def add (nums):----So, nums need to be an iterative object 2, variable positional parameter (an asterisk) a parameter can match any parameters x def add (*args):----Sum=0,for x in a RGS:----sum+=x3, variable keyword parameter (two asterisk) def add (**kwargs): For k,v in Kwargs.items (): Print ("{}={}". Format (K,V)) Add (x=1,y=2) can only be used  Keyword calls, consisting of a dictionary 4, mixed use parameters, variable parameters: 1, def showconfig (Username,password,**kwargs) 2, Def showconfig (Username,*args,**kwargs) 3, Def showconfig (username,password= "Mage", *args,**kwargs) 4, def fn (*args,x,y,**kwargs):----> So write, the call must be to the unique keyword x, Y for Keyword 5, fn (*,x,y) forces the X, Y to be the only keyword 6, the FN (*agrs,x=5) default value gives you the ability to call FN directly ()

Nine: Parametric deconstruction----real parameter deconstruction

1, FN (x, y): return (X+y) FN (* (4,5))/*[4,5]/*{4,5}/fn (*range (1,3))/fn (() [0],[3][0]) 2, dictionary deconstructed fn (**{x:5,y:6}) or FN (*  D.keys ()) or D.valus () 3, def fn (*args): print (args) fn (*[1,2,3]) 4, def fn (*args): sum = 0 for x in Args:sum + = x print (SUM)

Ten: Return value

11: Scope

1, an identifier of the visible range, that is, variables, generally speaking variable scope
2, x = 5 x = 5 def foo (): def foo (): Print (x) x+=1 foo () Print (x) executable, x is the global variable foo () is not enforceable, the x+=1 below is actually redefining the variable x, but does not exist
3, global scope, can be governed by the following functions, but the function of the interior of a high degree of autonomy, self-control local scope, local variables, inside can use external variables, but native variables, can only be used internally, external invisible
4. Nested structure Def outer ( ):                         def outer ( ):   o =  65                            o = 65  def inner ( ) :                          def inner ( ):       print (" inner { } ". Format (o))                  o = 97      print (Chr (o))                          print ("inner  { } ". Format (o))       print (" OUTER { } ". Format (o))                  print (Chr (o))    Inner ( )                               print ("OUTER { }". Format (o)) outer ( )       print 65,65,a                     inner ( )    external variables available internally, But assignment is defined                                   outer ( ) Print result 65,97,a
x = 5def foo ( ):    y = x+ 1   x = 1   print (x) foo ( ) error, assignment is defined, above x is not used, the following is not defined by Y to use the 
5. Global variable globalx = 5                                   def foo (): Def foo ():                             global  x   global  x                           x = 10    x+=1                               x +=1       declare x to use the outer global scope, the outside must have the definition of x                  This x=10 is a global variable that defines a variable for the outside 
6, Closure free variables: Variables that are not defined in the local scope, such as variable closures that define the scope of the outer function: appear in nested functions, The inner function refers to the free variable of the outer function Def counter ():   c = [0]  def inc ( ):     c[0] += 1    return c[0]  return incfoo  = counter ( ) print (foo ( ), Foo ( )) C = 100print (foo ( ))      Each time a local variable should disappear, but [ ] is a reference object, it changes every time, borrowing a reference type 
7, nonlocal keyword----keyword must not be occupied using the Nonlocal keyword, the variable is marked in the local scope of the ancestor defined, is the local scope of the ancestor, rather than the global scope function call why the loop count+=1??? Def counter (): Count = 0 def Inc (): nonlocal count Count +=1 return count return Incfoo = Counter () PR Int (foo (), foo ()) in the closure of the function, when the outside Foo called, the count of the variable is retained, and each time the execution of +1

8. Scope of function Default: (foo.__defaults__) use two underscore +defaults+ two underscore def foo (xyz=[]): Xyz.append (1) print (XYZ) print (foo (), ID (foo)) The default value of print (foo.__defaults__) print (foo (), ID (foo)) print (foo.__defaults__) does not change, the default value does not change, it is a tuple, but the list in the tuple has changed, which is a reference
def foo (w,u= "abc", z=123): U = "xyz" z = 456 print (w,u,z) print (foo.__defaults__) foo ("magedu") print (foo.__defaults__) Letter The default value of the number is not changed, and the re-assignment is displayed in the function call
9. Default value scope usage: def foo (xyz=[],u= "abc", Z=123): xyz=xyz[:] Xyz.append (1) print (XYZ) foo () print (foo.__defaults__) foo () Print (foo.__defaults__) foo ([foo.__defaults__) foo ([10,5]) print (foo.__defaults__) XYZ is re-assigned, made a copy, The original XYZ is still unchanged, the default value is always the same
def foo (xyz=none,u= "abc", Z=123): If XYZ is none:xyz=[] xyz.append (1) print (XYZ) foo () print (foo.__defaults__) foo ( ) print (foo.__defaults__) lst = [10]foo (LST) print (LST) print (foo.__defaults__) foo ([10,5]) print (foo.__defaults__) Using the immutable type default value, if none is used, a new list is created, and if, in a list, the list is modified, the LST changes, but the default value has not changed and is always a none,abc,123 tuple
def foo (x=none): if x = = None:x = [] x.append (1) return xlst = foo () a = foo (LST) print (a) Normally this function, Lst=foo () executes once Foo (), the result is [1],a=foo (LST) is executed again, and the result is []

12. Function Destruction:

Del or re-assign value

13. Tree:

1, the definition of:   (1), nonlinear deconstruction, each element can have multiple precursors and successors (this sentence, is the precursor 0 or 1, successor)   (2), the tree is a collection of n≥0 elements    (3), n =  0, is the empty tree, the root of the tree does not have a precursor   (4), the rest of the elements can only have a precursor, a plurality of subsequent 2, recursive definition:   (1), there is only one special element root, the remaining elements are divided into m disjoint set t1,t2 .... Tm, each set is a tree, called the subtree of T subtree   (2), subtree also has its own root 3, tree concept                                                                      (1), nodes, data elements in the tree, each element is a node   (2), the degree of the node degree: the number of sub-trees owned by the node, called Degrees, recorded as D (v), the degree of B is 1,c degree is 2,d degree is 3  (3), leaf node, The degree of the node is 0, it is leaf node leaf, terminal node, end node   (4), branch node, node degree is not 0, it is branch node   ABCDE  (5), branch, the relationship between nodes, A and B branches, relations, this line   (6), the internal node, the root and leaf node, the middle node   (7), the degree of the tree: Each node in the tree, whose degree is large, the degree of the tree is how much, for 3  (8), Children (son Child) node, nodes of the root of the sub-tree becomes the child of the node.   (9), parents (parent) node: A node is one of its various children.Parent   (10) of the root node of the tree, sibling node (sibling): nodes with the same parent node   (11), ancestor nodes: All nodes from the root node to the branch of the node. Abd are the ancestors of G   (12), descendants node: Nodes of all the sub-tree nodes are the descendants of the node, B's descendants are gdhi  (13), the level of the node: the root node is the first layer, the root of the child is the second layer, and so on, as L (v)   (14), the depth of the tree (height depth): The maximum level of the tree, the depth of 4  (15), the cousin, the parents on the same layer node 4, the concept of the tree:  (1), the ordered tree: the nodes of the subtree is sequential, cannot exchange   (2), Unordered Tree: Node subtree is unordered, can exchange   (3), Path: K node of tree n1,n2, ... NK, Meet NI is n (i+1) of the parents, become N1 to NK a path, is a line down, the former is the next parent node,a-b-d-g  (4), Path length: Nodes on the path -1  (5), Forest: M≥0 A collection of disjoint trees  d, E, F, subtree collection of nodes is the forest 5, the characteristics of the tree:  (1), the unique root   (2), the subtree does not intersect    (3), except the root, each element has only one precursor, 0 or more subsequent   (4), The root node has no precursor, the leaf node has no successor   (5), if VI is VJ's parents, then L (vi) =l (VJ)-1, parents than children level small 1  (6), cousin's parents are not necessarily brothers

14:2 Fork Tree

1. Up to two sub-trees per node: Two fork tree does not exist in degrees greater than two nodes 2, binary tree is ordered tree, left subtree, right subtree is sequential, cannot exchange 3, even if a node only a tree, also to determine whether it is Zuozi or right subtree 4, binary tree five form (1), Empty binary tree (2), Only the root node of the two-fork Tree (3), the root node only Zuozi (4), the root node only the right subtree (5), the root node has Saozi right sub-tree

XV, Oblique tree:

1, left oblique tree: All are left sub-tree 2, right oblique tree: All is right sub-tree

16, full two fork tree:

1, a binary tree all branches have Saozi right sub-tree, and leaf node only exist the bottom layer, one can not less, left and right completely symmetrical 2, the same depth, full two fork tree node up to 3, K for Depth (1≤k≤n), the total number of nodes is 2**k-1

17: Complete binary tree:

1, if the depth of the binary tree is k, then the number of layers of the two-fork tree from 1 to k-1 layer of nodes have reached the maximum number, all the nodes in K have been concentrated on the leftmost, this is the complete binary tree (the last layer, from left to right, not empty) 2, full two fork tree must be completely binary tree, complete binary tree is not necessarily full two fork tree 3, h on the left, if E has a branch node, then not, must d have two, E has a left subtree, is a complete binary tree

18, Binary Tree nature:

1. There are up to 2** (i-1) nodes on the first layer of the binary tree 2, depth is k two fork tree, at most 2**k-1 node 3, for any binary tree T, if its terminal node is n0, the degree of 2 of the node is N2, then there is n0=n2+1 (leaf node, is the degree of 2 nodes plus 1)      , leaf node n0=4 (HEFG), N2=3 (ABC) 4, leaf knot points-1 is equal to 2 of the number of points proof: n0+n1+n2=n (0 leaves, 1 degrees 1, 2 degrees 2): N0+n1+n2-1 (the number of branches of a tree is n-1 (total minus root node)) The number of branches is also equal to n0*0+n1*1+n2*2-----2n*2+n1 2*n2+n1=n0+n1+n2-1---->n2=n0-15, height is k two fork tree, at least k nodes (left oblique tree) 7, The depth of a complete binary tree with n nodes is int ((log2n+1)) n is +1 rounded, or Math.ceil (log2 (n+1)) 8, if there is a complete binary tree of n nodes, can follow the sequence number (1), if i=1, then node i is the root of the two fork tree, no parents If i>1, the parent is int (I/2) and rounded down. That is, the number of the sub-nodes is divisible by 2 to get the number of the parent node. Parent node If it is I, the left child node is 2i, right child is 2i+1 (2), if 2i>n, then the node has no left child, that is, node i is the leaf node, or the left child node exists numbered 2i (3), if 2i+1>n, then node I no right child, Otherwise the right child exists numbered 2i+1

19. Variable name resolution principle LEGB     

1, the local----the first domestic scope, call the end of the extinction 2, enclosing, nested function of the closure of the outer function of the namespace 3, global----, the interpreter exits 4, the build-in built-in module namespace, the interpreter starts to exit, Is the life cycle, print, open, etc.

20. Function Execution Flow:

1, the function execution flow:               global frame generates FOO1, 2, 3, Main Function Object Def foo1 (b,b1=3):               main function calls   print ("foo1 called", B,B1)       main to find the built-in function print stack , stack the constant string, call the function, pop the stack top Def foo2 (c):                   main Global lookup function Foo1 stack, press the constant 100,101 stack, call foo1 function,   foo3 (c)                     Create stack frame, print press stack, string and constant stack, call function, pop up stack top, return value.     print ("foo3 called", c)               Follow all similar Def foo3 (d):   print ("foo3 called", D) def main ():   Print ("main called")   foo1 (100,101)   foo2 ("  print") main called Main () 

21. Recursive recursion

1, the function calls itself directly or indirectly, is recursive

2. Boundary conditions are required for recursion

3, when the boundary conditions are not satisfied, recursive forward, when the boundary conditions are met, recursion ends.


This article from "13277682" blog, declined reprint!

Python Lesson Fourth----function

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.