跟着太白老师学python day10 函数嵌套, global , nonlocal

函数嵌套:

第一种嵌套方法

def func():
    count = 123
    def inner():
        print(count)
    inner()
func()

第二种嵌套方法

count = 123
def func_1():
    print(count)

def func_2():
    func_1()
func_2()

1. global

count = 0
def func1():
    global count  #把count变量变成全局变量,这样才可以修改,因为count在局部函数中没有定义
    count = count + 1
    print(count)
func1()
print(count)

2 . nonlocal 

def func2():
    count = 0
    def func3():
        nonlocal count   #子函数对父函数的变量进行修改,不然的话就只能引用父函数变量不能修改
        count = count + 1
        print(count)
    func3()
    print(count)
func2()
原文地址:https://www.cnblogs.com/my-love-is-python/p/9487649.html