python变量作用域

python变量作用域

制作人:全心全意

python中全局变量和局部变量可以同名,但互不干扰

a = 10
def myfun():
    a = 20
    print(a)
myfun()    #20
print(a)    #10

global和nonlocal的使用

a = 10
def myfun():
    a = 20
    def mynest():
        global a  
        a = 30
        print(a)    #30
    mynest()
    print(a)    #20
myfun()
print(a)    #30
a = 10
def myfun():
    a = 20
    def mynest():
        nonlocal a
        a = 30
        print(a)    #30
    mynest()
    print(a)    #30
myfun()
print(a)    #10

 

posted @ 2020-02-25 15:46  全心全意_运维  阅读(122)  评论(0编辑  收藏  举报