Python 因此,我需要将func2中的数字及其在func1中的定义增加1,并获取UnboundLocalError
所以我需要将func2中的数字和它在func1中的定义增加1。这里是代码:Python 因此,我需要将func2中的数字及其在func1中的定义增加1,并获取UnboundLocalError,python,python-3.x,Python,Python 3.x,所以我需要将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
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
将全局编号也放入func2中:
定义功能1:
全局数
数字=0
功能2
打印号码
定义功能2:
全局数
数字+=1
因为number在func2的作用域中不是局部变量,所以应该将其声明为全局变量
将功能2更改为:
def func2():
global number
number += 1