首页 > 解决方案 > UnboundLocalError:分配前引用的局部变量“uwu”

问题描述

哟,我试着做点什么,让我们说这是我的代码:

import threading
uwu = 0
def main():
    def e():
        if uwu > 10:
            print("no u")
            uwu += 1
        elif uwu <= 10:
            print('Hello, World!')
            uwu += 1
    done = False
    while not done:
        try:
            if threading.active_count() < 100:
                threading.Thread(target=e).start()
        except IndexError:
            done = True
            print("Done!")
            input()

main()

所以,当我执行它时,我得到了这个错误:

 File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "ask stacc xd.py", line 5, in e
    if uwu > 10:
UnboundLocalError: local variable 'uwu' referenced before assignment

如果有人可以帮助我解决这个问题,请回答或评论。

标签: pythonpython-3.xmultithreadingpython-multithreading

解决方案


您指的是全局变量。尝试使用global关键字。

import threading
uwu = 0
def main():
    def e():
        global uwu
        if uwu > 10:
            print("no u")
            uwu += 1
        elif uwu <= 10:
            print('Hello, World!')
            uwu += 1
    done = False
    while not done:
        try:
            if threading.active_count() < 100:
                threading.Thread(target=e).start()
        except IndexError:
            done = True
            print("Done!")
            input()

main()

推荐阅读