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

Python代码运行报错:light变量未定义,求解决方案

解决Python代码中"light变量未定义"的问题

错误根源

  1. light变量未覆盖所有分支初始化:只有当airlock输入为"y"时,light才会被赋值;如果输入非"y"/"n"的内容进入else分支,后续代码直接调用light就会触发未定义错误。
  2. lower方法调用错误:代码里写的airlock.lower和light.lower只是引用方法对象,没有实际执行方法,应该写成airlock.lower()和light.lower(),否则变量永远无法匹配"y"/"n"的判断条件,大概率会进入else分支,进一步触发light未定义问题。

修复方案

  • 给light设置初始默认值,或者用循环逻辑确保用户输入有效内容才继续;
  • 修正lower()方法的调用格式;
  • 优化重复的输入逻辑,用循环减少冗余代码。

修正后的代码

# 循环询问气压平衡状态,直到输入有效内容
while True:
    airlock = input("Has the air pressure equalised Y/N: ").lower()
    if airlock == "n":
        print("They wait until the air pressure equalises.")
    elif airlock == "y":
        break
    else:
        print("请输入Y或N")

# 循环询问指示灯状态,直到输入有效内容
while True:
    light = input("Does the airlock pressured light show green? Y/N: ").lower()
    if light == "n":
        print("The air lock continues to pressurise.")
    elif light == "y":
        print("The air lock is pressurised.")
        break
    else:
        print("请输入Y或N")

print("Corporal Alecks opens the inner airlock door and enters the moonbase with Commander Lorene")
print("Corporal Alecks takes Commander Lorene to the med bay")
print("Mission complete")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:15:48