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

Python代码报错UnboundLocalError:变量Numeral未赋值即引用

问题修复:UnboundLocalError 罗马数字验证代码

错误原因

当输入no时,你仅在yes分支中对Numeral进行了赋值,no分支下该变量完全未定义,后续直接调用valid_roman_numeral(Numeral)必然触发未绑定变量的错误。此外代码还遗漏了re模块的导入,内部嵌套函数也无必要,递归调用test()也不是最优的循环实现方式。

修复后的代码

import re

def valid_roman_numeral(numeral):
    return re.search(r"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$", numeral)

def test():
    while True:
        choice = input('Would you like to test a roman numeral? (yes/no)')  
        while choice != 'yes' and choice != 'no':
            choice = input("Sorry, invalid input. Please try again: ")
        
        if choice == 'no':
            print("Exiting program.")
            break
        
        # 仅在选择yes时执行验证逻辑
        numeral = input('Please enter the Roman numeral you would like to validate: ')
        if valid_roman_numeral(numeral):
            print("The numeral you have entered is correct!")
        else:
            print("The numeral entered does not follow Roman numeral rules. Please try again!")

test()

关键修改点

  • 导入re模块:原代码使用re.search但未导入模块,会触发NameError
  • 提取验证函数到外部:内部嵌套函数无必要,放在全局作用域更清晰
  • 新增no分支处理:直接退出循环,避免进入需要numeral变量的逻辑
  • 用循环替代递归:递归多次调用可能引发栈溢出,循环实现更安全高效
  • 变量名规范化:遵循Python PEP8命名规范,将大写变量名改为小写(如Test→choice,Numeral→numeral)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:15:22