What is the problem of using upper-level function variables in Python nested functions?

Why does the last two of the following three functions get an exception while the first one doesn"t?

def func(lst=[]):
    def inner_func():
        lst.append(10)
        return lst
    return inner_func()


def func2(num=10):
    def inner_func():
        num += 1
        return num
    return inner_func()


def func3(lst=[]):
    def inner_func():
        lst += [10]
        return lst
    return inner_func()


if __name__ == "__main__":
    print("func:", func())

    try:
        print("func2:", func2())
    except UnboundLocalError as e:
        print("func2:", e)

    try:
        print("func3:", func3())
    except UnboundLocalError as e:
        print("func3:", e)

execution result:

func: [10]
func2: local variable "num" referenced before assignment
func3: local variable "lst" referenced before assignment
Mar.12,2021

The variable scope of

python is divided into legb ( find a random blog post, you can learn about it )

in func2 and func3, you assign num and lst, resulting in the local scope of these two variables, and there is no initial value in the local variable (num + = 1 equals num = num + 1), so an error is reported.

clipboard.png

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b386a3-2ae56.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b386a3-2ae56.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?