因此,我需要从func2及其在func1中定义的数字增加1。继承人代码:
def func1():
global number
number = 0
func2()
print(number)
def func2():
number += 1
func1()
当我运行它时,出现此异常:
Traceback (most recent call last):
File "D:\global.py", line 10, in <module>
func1()
File "D:\global.py", line 4, in func1
func2()
File "D:\global.py", line 8, in func2
number += 1
UnboundLocalError: local variable 'number' referenced before assignment
Since
number
is not a local variable in the scope offunc2
, you should declare it asglobal
.Change
func2
to:Put
global number
inside func2() as well: