Detailed Python3 point function (parameter, anonymous function, scope, global variables and local variables)

The main content of the article made reference to rookie tutorial

Address: https://www.runoob.com/python3/python3-function.html

 

 

You may want to define a function by their own functions, the following simple rules:

  • In function block  def  beginning keyword, followed by the name and function identifier 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 indented
  • return [Expression]  End function, selectively returns a value to the caller. Return without an expression equivalent to return None.

You can change the (mutable) and can not be changed (immutable) objects

Repeat Assignment 1. Variables will only remember what the assignment later, generated a new variable of the same name, the original variables are deleted. Everything can serve as an object, because the variable is only a reference to an object.

And repeat the list of assignments and other variable type of a variable is to change the value of the variable.

2. immutable type numbers, strings, passed as a parameter tuple is passed by value, will not change itself; and the variable type list, a set of dictionaries passed as a parameter, is passed by reference, it will change itself.

 

parameter

There are four parameters: the parameters must, keyword parameters, default parameters, variable length parameter

Must parameters: the number of calls when necessary and when the same statement. Call printme () function, you must pass in a parameter, or a syntax error will occur.

Keyword arguments: Allows the order of calls, the number must be different than the time of declaration.

Default parameters: The DEF PrintInfo ( name , Age = 35 ) :

Variable-length parameters: Add an asterisk  * parameters will be introduced as a tuple (tuple), and storage of all variables unnamed parameters. Plus two asterisks  ** parameters will be introduced as a dictionary.

Example 1 (single *)

# ! / Usr / bin / python3 
  
# writable Function Description 
DEF printinfo (arg1, * vartuple):
    " Print any incoming parameter " 
   Print ( " Output: " )
    Print (arg1)
    Print (vartuple) 
 
# call printinfo function 
printinfo (70, 60, 50)

Results of the:

Output:
 70 
( 60,50)

 

Example 2 (2 *)

# ! / Usr / bin / python3 
  
# writable Function Description 
DEF printinfo (arg1, ** vartuple):
    " Print any incoming parameter " 
   Print ( " Output: " )
    Print (arg1)
    Print (vartuple) 
 
# call the function printinfo 
printinfo (70, a = 60, b = 50)

Results of the:

Output:
 70 
{ 'A': 60, ' B ' : 50}

 

 

Anonymous function

python using lambda to create an anonymous function.

grammar:

The lambda variable = [ arg1 [, arg2 , ..... argn ]]: expression The 

Examples

# ! / Usr / bin / to python3 
 
# Writable Function Description 
sum = the lambda arg1, arg2: + arg1 arg2 
 
# call the sum function 
Print ( " the added value: " , sum (10, 20 is ))
 Print ( " phase after adding the value: " , SUM (20 is, 20 is))

Results of the:

The value obtained by adding: 30 
of the added value:   40

 

 

Variable Scope

Rules: local scope can access the global scope, global scope can not access local scope.

Locally modify global scope when a scope like, using the keyword Global; if you want to modify nested scopes (the enclosing scope, outer scope), the keyword is required nonlocal

Python's scope, a total of four kinds:

  • L (Local) local scope
  • E (Enclosing) function outside the closure function
  • G (Global) global scope
  • B (Built-in) built scope (where the scope of the built-in function module)

To L -> E -> G - Rules> B lookup, namely: not found locally, will find a local (e.g., closure) to the outer partial, you will not find to find the global, addition to built-in look.

= 0 g_count   # global scope 
DEF Outer (): 
    o_count =. 1   # functions outer closure function 
    DEF Inner (): 
        the i_count = 2   # local scope

Built-in scope is achieved by a standard module called builtin, but the variable name itself is not built into the scope, so must import the files before you can use it. In Python3.0, you can use the following code to see in the end what predefined variables:

>>> import builtins
>>> dir(builtins)

Only Python module (Module1), class (class) and a function (def, lambda) before introducing a new scope, the other block of code (e.g., if / elif / else /, try / except, for / while, etc.) does not introduce a new scope, that variable defined within these statements, external can visit the following code:

>>> if True:
...  msg = 'I am from Runoob'
... 
>>> msg
'I am from Runoob'
>>> 

Msg variable is defined in the example if block but still be accessible outside.

If msg is defined in the function, then it is a local variable, not external access:

>>> def test():
...     msg_inner = 'I am from Runoob'
... 
>>> msg_inner
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'msg_inner' is not defined
>>> 

 

 

Global variables and local variables

It is defined as having a local scope, defined outside the function has global scope within a function of the variables.

The local variables can be declared within its access function, and can access the global variables in the entire program range. When you call a function, all variables declared within a function name will be added to the scope.

For chestnut:

# ! / Usr / bin / to python3 
 
Total = 0 # This is a global variable 
# Writable Function Description 
DEF SUM (arg1, arg2):
     # . Returns two parameters and a " 
    Total = arg1 + arg2 # Total here is a fragmentary variable 
    Print ( " the function is a local variable: " , Total)
     return Total 
 
# call the sum function 
sum (10, 20 is )
 Print ( " external function is a global variable: " , Total)

Results of the:

Local variables inside a function: 30 
external function is a global variable: 0

 

global and nonlocal keyword

1. When you want to modify the scope of the internal variable outer scope, it is necessary to use a global and nonlocal keyword.

For chestnut:

#!/usr/bin/python3

NUM = 1
 DEF fun1 ():
     global NUM   # need to use the global keyword to declare 
    Print (NUM) 
    NUM = 123
     Print (NUM) 
fun1 () 
Print (NUM)

Results of the:

1
123
123

To modify nested scopes (the enclosing scope, the outer non-global scope) of the variable keyword is required nonlocal, chestnut follows:

# ! / Usr / bin / python3 
 
DEF Outer (): 
    NUM = 10
     DEF Inner (): 
        nonlocal NUM    # nonlocal keyword to declare 
        NUM = 100 Print (NUM) 
    Inner () Print (NUM) 
Outer ()
        
    

Results of the:

100
100

 

2. Modify a global variable that is passed through the function parameters can be performed as a normal output:

#!/usr/bin/python3
 
a = 10
def test(a):
    a = a + 1
    print(a)
test(a)

Results of the:

11

 

Guess you like

Origin www.cnblogs.com/Luoters/p/11423904.html