You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python变位词项目报UnboundLocalError变量引用错误如何修复?

报错原因

UnboundLocalError: local variable 'running' referenced before assignment 报错的核心原因是:你在main()函数内的while running:语句中直接引用了running变量,但在执行到这行代码前,你没有在函数内部给running变量做过初始化赋值,Python无法找到该变量的定义,因此抛出错误。
你仅在循环内部用户选择退出时才给running赋值为False,但代码执行顺序是先判断循环条件再进入循环体,还没进入循环就用到了未定义的变量,自然会触发报错。

修复方案

你只需要在main()函数开头、while循环执行之前,给running变量赋初始值True即可解决当前报错。
另外你当前贴出的代码还有几处明显错误,也需要同步修改才能正常运行:

  • 你初始将phrase赋值为布尔值True,后续却执行phrase += choice + ' '的字符串拼接操作,会触发类型错误,需要将phrase初始值改为空字符串""
  • 你用到了sys.stderr、sys.exit(),需要在代码开头导入sys模块
  • 代码中用到的user_word、dict_file变量,以及find_anagram、process_choice函数需要提前定义完成

修改后的核心代码片段如下:

import sys

# 请提前定义好find_anagram、process_choice函数
# 请提前加载词典文件到dict_file变量

def main():
    running = True
    # 补充获取用户输入的逻辑
    user_word = input("请输入要生成变位短语的名称:")
    name = ''.join(user_word.lower().split())
    name = name.replace('-','')
    limit = len(name)
    phrase = ""

    while running:
        temp_phrase = phrase.replace(' ', '')  
        if len(temp_phrase) < limit:
            print(f"length of anagram phrase = {len(temp_phrase)}")

            find_anagram(name, dict_file)
            print("Current anagram phrase =", end = " ")
            print(phrase, file=sys.stderr)

            choice, name = process_choice(name) 
            phrase += choice + ' '

        elif len(temp_phrase) == limit:
            print("\n**FINISHED!!**\n")
            print("Anagram of name", end = " ")
            print(phrase, file=sys.stderr)
            print()
            try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
            if try_again.lower() == 'n':
                running = False
                sys.exit()
            else:
                main()

内容的提问来源于stack exchange,提问作者Karthik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 10:45:10