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

Python UnboundLocalError求助:变量number赋值前被引用

解决你的UnboundLocalError问题

嘿,这个问题我见过不少编程新手碰到,咱们来拆解一下到底咋回事:

问题根源

当你第一次输入非数字(比如hkjadhjkas)时,try块里的number = int(input("--> "))执行失败,直接跳到except块:

  • 打印"Not a number!"
  • 调用straight()递归,让用户重新输入

等这次递归执行完成(比如你输入20成功通过),程序会回到上一层的straight()函数,继续执行后面的代码:if number % 2 == 0:——但这一层的number变量根本没被赋值!因为刚才的try块失败了,number从未被定义,所以就抛出了UnboundLocalError。

而第一次直接输入数字时,try块成功给number赋值,后面的判断能正常执行,所以不会报错。

修复方案

方案1:快速修复递归逻辑

最直接的修复是,在except块调用递归后,加上return,让函数直接终止,不再执行后面未定义number的代码:

def straight(): 
    print("You went straight ahead") 
    print("You run into a locked door. You try to break down the door but it doesn't work..") 
    print("Then you see the writing on the wall next to the door..") 
    print("Call a number and then we call it even!") 
    try: 
        number = int(input("--> ")) 
    except: 
        print("Not a number!")
        straight()
        return  # 加这一行,避免执行后面未定义number的代码
    if number % 2 == 0: 
        print(f"You cracked the code! Your even number {number} gave you access to this door") 
        print("The door opens..") 
        final_room() 
    elif number % 2 >= 1: 
        dead(f"The wrong number ({number}) caused the tunnel to collapse!") 
    else: 
        print("test else?") 
        straight() 

方案2:用循环代替递归(更推荐)

递归如果遇到用户多次输入错误,可能会触发函数调用栈溢出,用循环处理输入验证更安全:

def straight(): 
    print("You went straight ahead") 
    print("You run into a locked door. You try to break down the door but it doesn't work..") 
    print("Then you see the writing on the wall next to the door..") 
    print("Call a number and then we call it even!") 
    
    # 循环直到用户输入有效的数字
    while True:
        try: 
            number = int(input("--> ")) 
            break  # 输入正确,跳出循环
        except: 
            print("Not a number! Please try again.")
    
    if number % 2 == 0: 
        print(f"You cracked the code! Your even number {number} gave you access to this door") 
        print("The door opens..") 
        final_room() 
    else: 
        dead(f"The wrong number ({number}) caused the tunnel to collapse!") 

(注:这里把elif number %2 >=1改成了else,因为整数要么是偶数要么是奇数,没必要额外判断)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:29:08