修复围绕 "local variable ' ' referenced before assignment." 的 UnboundLocalError

Fixing UnboundLocalError revolving around "local variable ' ' referenced before assignment."

我正在尝试使用模块执行翻译,但不断收到与我的某些变量相关的错误消息:

UnboundLocalError: local variable 'usedWord' referenced before assignment

这是我的参考代码:

def message_translate():
    for message in r.get_unread():
        message_text = message.body.lower()
        messageList = message_text.split()
        for word in message_text:
            if word in fullLangNames:
                usedWord = word
                index = fullLangNames.index(word)
                transLang = supportedLangs[index]
            elif word in abbrevLangNames:
                usedWord = word
                index = abbrevLangNames.index(word)
                transLang = supportedLangs[index]

        finalized_message_text = message_text.replace("/u/pleaseTranslate", "") and message_text.replace(usedWord, "")
        translation = (translator.translate(finalized_message_text, lang_from = 'en', lang_to = transLang))
        callback = (transMessage % translation)
        message.mark_as_read

现在我不明白为什么我会收到那个错误,或者这个错误告诉我什么。如果这是一个简单的修复,我深表歉意,虽然我环顾四周并没有发现任何重要用途。

谢谢,感谢您的帮助!

在我看来,问题出在 finalized_message_text。您应该在 for 循环之前初始化 usedWord = ""。那应该解决它。或者添加最后的 Else 语句来初始化 usedWord = ""