Road Python Python global variables and local variables, nested functions, recursive function

First, local variables and global variables

 

1, the variable defined in a local variable called subroutine, the variable a defined at the beginning in a program called global variables. Global variable scope is the entire program, the local variable scope is defined subroutines of the variable.

Global variables without any indentation, can be called at any position.

 

Subroutine: The function defined with def.

 

Scope

The visible range of an identifier, which is the scope identifier. General often said that the variable scope

Global scope (global): visible throughout the program runtime environment

Local scope: visible internal functions, etc.; local variable range in which it can not exceed the local scope.

 

example

NAME = "nicholas"
def change_NAME():
    print("change_NAME", NAME)
change_NAME()
print(NAME)

 


Output

change_NAME nicholas
nicholas

 


Analysis: NAME = "nicholas" is a global variable, in
change_NAME () function in vivo can be called to print out "change_NAME nicholas" directly

 

2, when the same name as a global variable and a local variable:


In subprogram within the definition of local variables, local variables play a role; global variables to function elsewhere.

example:

 

NAME = "nicholas"
def change_NAME():
    NAME = "niubi"
    print("change_NAME", NAME)
change_NAME()
print(NAME)

 

  

Output

change_NAME niubi
nicholas

 

Analysis: When the global variables and local variables of the same name: the def change_NAME (): internal function,
executing print ( "change_NAME", NAME) statement, NAME where the priority value inside the function call, perform print after the function is executed (NAME ) statement, global variables NAME = "nicholas" work.


3, if the internal function without global keyword


Priority read local variables, local variables are read if there is no global variables can not be assigned at this time of global variables.

But for mutable object can be manipulated (e.g., append () pop ()) of the internal element.

 

Premise: no global keyword

a, with a statement (synonym) local variable
Examples

Copy the code
name = ["pony","jack"]
print(1,name)
def change_name():
    name = "nicholas"
    print("change_name", name)
change_name()
print(2,name)
Copy the code


Output

1 ['pony', 'jack']
change_name nicholas
2 ['pony', 'jack']
1 ['pony', 'jack']
change_name nicholas
2 ['pony', 'jack']

 

  

Analysis: Here golbal no keyword, execute print (1, name) when the statement is read global variable name = [ "pony", " jack"], after performing Change_Name () function, the function which is assigned nema "nicholas"
execute print ( "change_name", name) statement, name local variable read priority here inside the function name = "nicholas"
output change_name nicholas. After change_name () function ends.
Execute print (2, name) statement. There is still reading the global variable name = [ "pony", " jack"].


b, no declaration (synonym) local variable
Examples

Copy the code
name = ["pony","jack"]
print(1,name)
def change_name():
    print(3, name)
    name.append("nicholas")
    print(4,name)
change_name()
print(2,name)
Copy the code

 

  


Output

1 ['pony', 'jack']
3 ['pony', 'jack']
4 ['pony', 'jack', 'nicholas']
2 ['pony', 'jack', 'nicholas']

 

  


Analysis: No global keyword for global variables if a variable object, you can operate on internal elements.

 

4, if there is global 'keyword, the variable is essentially a global variable, it can be assigned reading.

 

a, with a statement (synonym) local variables

example

Copy the code
NAME = "nicholas"
print(1,NAME)
def change_NAME():
    global NAME
    NAME = "niubi"
    print("change_NAME", NAME)
change_NAME()
print(2,NAME)
Copy the code

 

  

Output

Nicholas. 1 
Change_Name niubi 
2 niubi

 

  

Analysis: In the implementation of print ( "1", NAME) when the statement, NAME use global variables, and then execute change_NAME () function inside the function have global keyword statement, after performing NAME = "niubi", after executing the entire sentence NAME variable value of the program was changed to "niubi".
Continues to output change_NAME niubi, the end of the function.

Finally, the implementation of print ( "2", NAME) statements, since the inside NAME modified function "niubi", so here the output
2 niubi

 


Example 2

Copy the code
name = ["pony","jack"]
print(1,name)
def change_name():
    global name
    name = ["nick"]
    name.append("nicholas")
    print(3,name)
change_name()
print(2,name)
Copy the code

 



Output

1 ['pony', 'jack']
3 ['nick', 'nicholas']
2 ['nick', 'nicholas']

 

Analysis:
start name = [ "pony", " jack"] is a global variable, after performing change_name () function do with the global keyword in the function, then for name changes made are the equivalent of the name as a global variable to modify .


c, pay attention to global position

 

Error examples

 

  

Analysis: If you need to modify global global variables can not be placed where the global name = "nick" below.

 

 

5, the code specification: global variables all uppercase letters, lowercase variable name local variable.


Second, the multi-layer functions and nested scopes


(1) Note that the function must be defined first, after use
example 1

def test1():
    print("test1")
def test2():
    print("test2")
test1()
test2()

 


Analysis: This is possible, by defining the function, then use the function

Error examples

def test1():
    print("test1")
test2()
def test2():
    print("test2")
test1()

 

  


Analysis: This test2 () will not be executed.

(2) function defined in the function can not be used outside


Example 2

def outer():
    def inner():
        print('inner')
    print('outer')
    inner()
outer()

 

  


Analysis: Functions visible range, which is the concept of scope. Internal external function can not be used directly.

example

def foo():
    print("foo")
    too()
def too():
    print("too")
foo()

 

  


Analysis: Here the order of execution is loaded def foo ():
Load def too (): and then execute foo (), so there will not be an error.

(3) Analysis and results of execution nested function
example

Copy the code
NAME = 'nicholas'
def jack():
    name = "jack"
    print(name)
    def pony():
        name = "pony"
        print(name)
        def charles():
            name = 'charles'
            print(name)
        print(name)
        charles()
    pony()
    print(name)
jack()
Copy the code

 


Output:

jack
pony
pony
charles
jack

 

analysis:

FIG performed as follows

 

Execution order: 1. 3 ---- 2 ---- ---- ---- 3.1 3.2 ---- 3.3 ---- 3.4 ---- ---- 3.3.1
3.3.2-- 3.3.4 --3.3.3 ---- ---- ---- 3.5 3.3.5--3.3.3.1--3.3.3.2

 

1 first performs NAME = 'nicholas' statement

2 Load def jack (): memory function to be compiled, but does not perform

3 Call jack () function, started

3.1 执行name = "jack"语句

3.2 执行print(name)语句,这里由于没有global关键字,优先读取局部变量name = "jack",所以这里输出jack

3.3 加载def pony():函数到内存进行编译,但不执行

3.4 调用pony():函数,开始执行

3.3.1 执行name = "pony"语句,这里是一个局部变量

3.3.2 执行print(name)语句,这里由于没有global、nonlocal关键字,优先读取局部变量name = "pony",所以这里输出pony

3.3.3 加载charles():函数到内存进行编译,但不执行

3.3.4 执行print(name)语句,这里由于没有global、nonlocal关键字,优先读取同一层级的局部变量name = "pony",所以这里输出pony

3.3.5 调用charles():函数,开始执行

3.3.3.1 执行name = 'charles'语句,这里是个局部变量

3.3.3.2 执行print(name)语句,优先读取局部变量name = "charles",所以这里输出charles

~~charles():函数结束

~~pony():函数


3.5 执行执行print(name)语句,优先使用同层级的局部变量name = "jack",所以这里输出jack。


~~整体结束

 

例子

 

Copy the code
name = "nicholas"
def outer():
    name = "nick"
    def inner():
        print(name)
    print(name)
    inner()
outer()
Copy the code

 

 

输出结果

 

nick
nick

 

  分析:注意这里的inner()函数内部的print(name)语句,这里仍然是优先使用outer()函数内部的局部变量name = "nick",而非全局变量。

 

(4)

nonlocal关键词
nonlocal,指定上一级变量,如果没有就继续往上直到找到为止
例子
看这个程序,分析输出过程和结果。

 

Copy the code
def scope_test():
    def do_local(): 
        spam = "local spam"  
    def do_nonlocal(): 
        nonlocal spam 
        spam = "nonlocal spam"   
    def do_global(): 
        global spam 
        spam = "global spam"       
    spam = "test spam"
    do_local()
    print("After local assignment:", spam)
    do_nonlocal()
    print("After nonlocal assignment:", spam)
    do_global()  
    print("After global assignment:", spam)       
scope_test()
print("In global scope:", spam)
Copy the code

 

  

输出结果

After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam

 

  

分析:
程序执行步骤如图

 

 

从1开始
1--2--2.1--2.2--2.3--2.4--2.5--2.5.1--2.5.2--2.6--2.7--2.7.1--2.7.2--2.8

--2.9--2.9.1--2.9.2--2.10--2.11


下面具体分析下程序执行的过程

1 将def scope_test():函数体作为一个整体加载到内存中,但不执行

2 调用def scope_test():开始执行

2.1 将def do_local():函数体作为一个整体加载到内存中,但不执行

2.2 将def do_nonlocal(): 函数体作为一个整体加载到内存中,但不执行

2.3 将 def do_global(): 函数体作为一个整体加载到内存中,但不执行

2.4 执行 spam = "test spam"

2.5 调用 def do_local():函数

2.5.1 执行 def do_local():函数

2.5.2 执行 spam = "local spam"

--完成2.5.2之后 def do_local():函数结束,其所占的内存被回收, spam =

"local spam"数据被销毁

2.6 执行print("After local assignment:", spam)语句

由于没有global关键字,这里优先读取局部变量,即spam = "test spam"

打印出After local assignment: test spam

2.7 调用do_nonlocal()函数

2.7.1 执行def do_nonlocal():

遇到 nonlocal 声明,nonlocal关键字用来在函数外层(非全局)变量。

这里的外层即为def scope_test():这个作用域内

2.7.2 执行spam = "nonlocal spam"语句

这时def scope_test():这个作用域内由以前的spam = "test spam"被重新覆盖为

spam = "nonlocal spam"

--do_nonlocal()函数体结束

2.8 执行 print("After nonlocal assignment:", spam)语句

由于spam被重新赋值为"nonlocal spam",这里输出

After nonlocal assignment: nonlocal spam

2.9 调用do_global()函数

2.9.1 执行def do_global(): 函数

2.9.2 执行 spam = "global spam" 语句

遇到global声明,global关键字用来在函数整体作用域使用全局变量。类似于在

def scope_test():上面写了一句spam = "global spam"

--def do_global(): 函数体结束

2.10 执行print("After global assignment:", spam)语句

由于这一层级作用域没有global关键字,这里优先读取局部变量,即被修改过一次的

spam = "nonlocal spam"

这里输出After global assignment: nonlocal spam

2.11执行print("In global scope:", spam)语句

由于在2.9.2 spam被声明了全局变量,即spam = "global spam"

所以这里输出

In global scope: global spam

 

例子2

Copy the code
name = "jack"
def foo():
    name = "nick"
    print(name)
    def too():
        nonlocal name
        name = "nicholas"
        print(1,name)
    too()
    print(name)
foo()
Copy the code

 

  输出结果

nick
1 nicholas
nicholas

 

  分析:注意这里的def too():函数内print(1,name)语句仍然优先读取局部变量name = "nicholas"。


三、递归


1、递归的定义


如果在调用一个函数的过程中直接或间接调用自身本身,那么这种方法叫做递归。

 

2、递归的特点


a、递归必须有一个明确的结束条件(基例)。
b、每次进入更深一层递归时,问题规模相比上次递归都应有所减少。
c、递归效率不高,递归层次过多会导致栈溢出。


3、递归的执行过程

例子

def calc(n):
    print(n)
    if int(n/2) ==0:
        return n
    return calc(int(n/2))
calc(10)

 

  


输出结果

10
5
2
1

 


分析执行过程:

 

具体过程

(1)执行def calc(n):语句,将calc(n)函数加载到内存中进行编译,但不执行


(2)执行calc(10)语句,调用calc(n)函数,将n = 10 传入calc(n)函数


(3)执行print(n)语句,此时n = 10,打印10


判断n/2是否等于0,10/2 = 5不等于0


执行retun语句,return调用calc(n)函数,


此时具体是执行calc(int(10/2))即calc(5)


此层函数暂停,等待calc(5)返回值


(4)执行print(n)语句,此时n = 5,打印5


判断n/2是否等于0,5/2 = 2不等于0


执行retun语句,return调用calc(n)函数,


此时具体是执行calc(int(5/2))即calc(2)


此层函数暂停,等待calc(2)返回值


(5)执行print(n)语句,此时n = 2,打印2


判断n/2是否等于0,2/2 = 1不等于0


执行retun语句,return调用calc(n)函数,


此时具体是执行calc(int(2/2))即calc(1)


此层函数暂停,等待calc(1)返回值


(6)执行print(n)语句,此时n = 1,打印1


判断n/2是否等于0,1/2 = 2等于0,


执行if条件下的retun语句,return n 给上一层函数,


即return 1给上层函数


(7)将1传给calc(1),calc(1)得到值为1 ,


return calc(1)即return 1,再次将1传给上层的return calc(2),


calc(2)得到值为1,再次将1传给上层的return calc(5),


calc(5)得到值为1,最后将1传给calc(10),


即calc(10)= 1。

 

这里可以打印下calc(10)的值

Copy the code
def calc(n):
    print(n)
    if int(n / 2) == 0:
        return n
    return calc(int(n / 2))
v = calc(10)
print("calc(10)是",v)
Copy the code

 

  输出结果

10
5
2
1
calc(10)是 1

 

  

 

例子2

 

Copy the code
import time
person_list=['Pony','Charles','Richard ','Jack']
print("How can I make good money?")
def ask(person_list):
    print('-'*60)
    if len(person_list) == 0:
        return "I don't know"
    person=person_list.pop(0)
    if person == "Jack":
        return "%s say:Better have a dream, in case it comes true someday." %person
    print('hi Boss[%s],How can I make good money?' %person)
    print("%s replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask %s..." %(person,person_list))
    time.sleep(10)
    res=ask(person_list)
    #print('%s say: %res' %(person,res))#注释语句
    return res
 
res = ask(person_list)
 
print(res)
Copy the code

 

  


输出结果

Copy the code
How can I make good money?
------------------------------------------------------------
hi Boss[Pony],How can I make good money?
Pony replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Charles', 'Richard ', 'Jack']...
------------------------------------------------------------
hi Boss[Charles],How can I make good money?
Charles replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Richard ', 'Jack']...
------------------------------------------------------------
hi Boss[Richard ],How can I make good money?
Richard  replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Jack']...
------------------------------------------------------------
Jack say:Better have a dream, in case it comes true someday.
Copy the code

 

  

 

如果取消上面print('%s say: %res' %(person,res))注释,执行这一语句,可以看出return返回的过程
如下

Copy the code
import time
person_list=['Pony','Charles','Richard ','Jack']
print("How can I make good money?")
def ask(person_list):
    print('-'*60)
    if len(person_list) == 0:
        return "I don't know"
    person=person_list.pop(0)
    if person == "Jack":
        return "%s say:Better have a dream, in case it comes true someday." %person
    print('hi Boss[%s],How can I make good money?' %person)
    print("%s replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask %s..." %(person,person_list))
    time.sleep(1)
    res=ask(person_list)#第一处
    print('%s say: %res' %(person,res))
    return res
 
res = ask(person_list)#第二处
 
print(res)
Copy the code

 


输出结果

Copy the code
How can I make good money?
------------------------------------------------------------
hi Boss[Pony],How can I make good money?
Pony replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Charles', 'Richard ', 'Jack']...
------------------------------------------------------------
hi Boss[Charles],How can I make good money?
Charles replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Richard ', 'Jack']...
------------------------------------------------------------
hi Boss[Richard ],How can I make good money?
Richard  replied:I don't know,But I konw you are a smart boy,hold on ,I can help you ask ['Jack']...
------------------------------------------------------------
Richard  say: 'Jack say:Better have a dream, in case it comes true someday.'es
Charles say: 'Jack say:Better have a dream, in case it comes true someday.'es
Pony say: 'Jack say:Better have a dream, in case it comes true someday.'es
Jack say:Better have a dream, in case it comes true someday.
Copy the code

 

  

Analysis: The final result is returned back to Richard Charles, Charles returned to the Pony
RES at first = ask (person_list) even if the execution is over, res get Jack say: Better have a dream, in case it comes true someday.

Then return to the res outside the function, the last print this sentence.

Guess you like

Origin www.cnblogs.com/QaStudy/p/11514928.html