Wu Yuxiong - born natural python learning Notes: Python3 function

Tissue function is good, reusable, code segments used to implement a single, or the associated function. 

Function module of the application can be improved, and code reuse. You already know that Python provides many built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions. 

Define a function 
you can define a function of the desired function by themselves, the following rules are simple: 

the function code blocks def begins with keyword followed by the function name and identifiers in parentheses (). 
Any incoming parameters and arguments in parentheses must be placed in the middle, between parentheses may be used to define the parameters. 
The first statement function can be selectively used documentation string - for storing function instructions. 
Start function contents colon, and indentation. 
return [Expression] End function, selectively returns a value to the caller. Return without an expression equivalent to return None.
Syntax 
Python-defined functions using def keyword, the general format is as follows: 

def function name (parameter list): 
    function body 
default parameter values and parameter names are defined in the function declaration in order to match up.
>>>def hello() :
   print("Hello World!")
 
   
>>> hello()
Hello World!
# 计算面积函数
def area(width, height):
    return width * height
 
def print_welcome(name):
    print("Welcome", name)
 
print_welcome("Runoob")
w = 4
h = 5
print("width =", w, " height =", h, " area =", area(w, h))
Function call 
definition of a function: the function of a given name, contains parameters specifying the function, and the code block structure. 

After completion of the basic structure of this function, you can call performed by another function can be performed directly from the Python command prompt. 

The following examples are called printme () function: 
# -defined functions 
DEF PrintMe (str):
    # print any incoming string 
   Print (str)
    return 
 
# call the function 
PrintMe ( " I want to call a user-defined function! " ) 
PrintMe ( " calls the same function again . " )
Parameters passed 
in python, belong to the object type, the variable type is not: 

A = [2,3 ] 

A = " Runoob " 
Above, the [ 1,2,3] type is List, " Runoob " a String type, and the variable is not a type, she is just an object reference (a pointer), may be pointing to an object of type List, it can be pointed objects of type String.
Can be changed (the mutable) and can not be changed (the immutable) objects 
in python, strings, tuples, and numbers are immutable objects, the list, dict the other objects can be modified. 

Immutable type: Variable Assignment a = 5 then the assignment a = 10, where int is actually generate a new value object 10, let a point to it, and 5 are dropped, instead of changing the value of a, a is newly equivalent . 

Variable Type: Variable Assignment la = [1,2,3,4] then assigned la [2] = 5 third element values change sucked List la, la in itself did not move, only part of the value of its internal It is modified. 

python parameter transfer function: 

immutable: Similar C ++ passed by value, such as integer, string, a tuple. The value Fun (a), only a transfer of a subject itself has no effect. Such modifications (a) an internal value of a fun, but modify the object copied to another, it does not affect a per se. 

Variable types: Similar to c ++ is passed by reference, such as lists, dictionaries. As fun (la), sucked la real pass in the past, the revised fun outside la also be affected 

everything is an object in python, in the strict sense we can not say passed by reference or value transfer, we should say pass immutable objects and pass variable objects.
DEF ChangeInt (A): 
    A = 10 
 
B = 2 
ChangeInt (B) 
Print (B) # result 2
Instance there int objects 2, pointing to its variables b, when passed to ChangeInt function, by way of traditional values ​​copied variable b, a and b point to the same Int object, a = 10, then the new generating an int value object 10, and let a point to it.
Pass variable object instance 
variable object to modify the parameters in the function, then the function call this function, the original parameters have been changed. For example: 
# writable Function Description 
DEF changeme (mylist):
    " Modify the incoming list " 
   mylist.append ([ 1,2,3,4 ])
    Print ( " within a function value: " , mylist)
    return 
 
# calls changeme function 
mylist = [10,20,30 ] 
changeme (mylist) 
Print ( " external function value: " , mylist)
Parameters 
The following are the formal parameter type can be used when calling a function: 

Required parameter 
keyword arguments 
default parameters for 
variable length parameters
Required parameters 
required parameters in the correct order to be passed to the function. When the number of calls and the same must be declared when. 

Call printme () function, you must pass in a parameter, or will a syntax error
# Write Function Description 
DEF printme (str):
    " Print any incoming string " 
   Print (str)
    return 
 
# calls printme function without parameters will complain 
printme ()
Keyword arguments 
keyword arguments and function call close relationship function call using keywords to determine the parameters passed in parameter values. 

When you use keyword parameters and allows the order parameter of the function call statement is inconsistent, because the Python interpreter to match the parameter value with the parameter name. 

The following example uses the function printme () is invoked Parameter name: 
# write Function Description 
DEF printme (str):
    " Print any incoming string " 
   Print (str)
    return 
 
# calls printme function 
printme (str = " rookie tutorial " )
The following example illustrates the use of function parameters do not need to specify the order:
 # write Function Description 
DEF the PrintInfo (name, Age):
    " Print any incoming string " 
   Print ( " name: " , name)
    Print ( " Age : " , Age)
    return 
 
# calls printinfo function 
printinfo (Age = 50, name = " runoob " )
The default parameters 
when calling the function, if the parameter is not passed, the default parameters will be used. The following examples if no incoming age parameter, the default value: 
# write Function Description 
DEF the PrintInfo (name, age = 35 ):
    " Print any incoming string " 
   Print ( " name: " , name)
    Print ( " Age: " , Age)
    return 
 
# calls printinfo function 
printinfo (Age = 50, name = " runoob " )
 Print ( " ----------------------- - " ) 
the PrintInfo (name = " runoob " )
Variable-length parameters 
you might need a function that can handle more parameters than the original statement. These parameters, called variable length parameters, and the above-mentioned 2 types of parameters different, not naming declaration. The basic syntax is as follows: 

DEF functionName ([formal_args,] * var_args_tuple):
    " function _ Document string " 
   function_suite 
   return [expression The] 
plus asterisk * parameter will be introduced in the tuple (tuple) form, store all unnamed variable parameters
# Write Function Description 
DEF printinfo (arg1, * vartuple):
    " Print any incoming parameter " 
   Print ( " Output: " )
    Print (arg1)
    Print (vartuple) 
 
# call printinfo function 
printinfo (70, 60, 50)
# Write Function Description 
DEF printinfo (arg1, * vartuple):
    " Print any incoming parameter " 
   Print ( " Output: " )
    Print (arg1)
    for var in vartuple:
       Print (var)
    return 
 
# calls printinfo function 
printinfo (10 ) 
PrintInfo ( 70, 60, 50)
Another is the parameter with two asterisks ** The basic syntax is as follows: 

DEF functionName ([formal_args,] ** var_args_dict):
    " function _ documentation strings " 
   function_suite 
   return [expression The] 
added two asterisks parameters of ** It will be introduced as a dictionary.
# Write Function Description 
DEF printinfo (arg1, ** vardict):
    " Print any incoming parameter " 
   Print ( " Output: " )
    Print (arg1)
    Print (vardict) 
 
# call printinfo function 
printinfo (1, a = 2, b = 3)
Function is declared, the asterisk * Parameter may appear alone, for example: 

DEF F (A, B, * , C):
     return A + B + C 
if a single asterisk parameters must be passed by the * key.
Anonymous function 
python using lambda to create an anonymous function. 

The so-called anonymous, which means no longer using the def statement of such standards in the form of a defined function. 

lambda is just an expression, function body than def much simpler. 
lambda expression is a body, instead of a code block. We can only package a limited logic into the lambda expression. 
lambda function has its own namespace, and can not be accessed outside its own parameter list or the global namespace parameters. 
Although lambda function looks can only write a single line, but not equivalent to C or C ++ inline function, which aims not take up the stack memory when calling small functions to increase operating efficiency. 
Syntax 
lambda syntax function contains only one statement, as follows: 

lambda [arg1 [, arg2, ..... argn]]: expression The
# Writable Function Description 
sum = the lambda arg1, arg2: + arg1 arg2 
 
# call the sum function 
Print ( " the added value: " , sum (10, 20 is ))
 Print ( " a value obtained by adding: " , sum (20, 20))
return statement
 return [Expression] is used to exit the function, an expression selectively returns to the caller. Return statement with no parameter values return None. Examples of prior not demonstrate how to return a value, the following examples demonstrate the return statement usage:
 # Writable Function Description 
DEF SUM (arg1, arg2):
    # Returns the two parameters and. " 
   Total = arg1 + arg2
    Print ( " Function within: " , Total)
    return Total 
 
# call the sum function 
Total = sum (10, 20 is )
 Print ( " external function: " , Total)
Forced location parameter 
Python3. . 8 adds a function parameter syntax / is used to indicate the function parameter specified location parameters must not be used in the form of keyword parameter. 

In the following example, the parameter a and position parameter b be specified, c or d may be a position parameter or keyword parameter, and e or f key parameter requirements

 

Guess you like

Origin www.cnblogs.com/tszr/p/12001206.html