所以我需要从func2及其在func1中定义的数字增加1,并获得UnboundLocalError

因此,我需要从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 of func2, you should declare it as global.

    Change func2 to:

    def func2():
        global number
        number += 1
    
  • 命*
    命* 回复

    Put global number inside func2() as well:

    def func1():
      global number
      number = 0
      func2()
      print(number)
    
    def func2():
      global number
      number += 1