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

Python中已定义swim_or_wait却报NameError问题求助

问题分析与解决

错误原因

当用户输入"right"时,代码会执行第一个if direction == "right"分支,仅打印"Game over.",不会进入else分支定义swim_or_wait变量。但后续代码直接尝试判断swim_or_wait的值,此时该变量从未被创建,因此触发NameError。

另外,原代码存在一个小问题:input("Left or right? ".lower())中的.lower()是作用于提示字符串本身,而非用户输入的内容,这会导致输入大小写不统一的匹配问题,正确写法应该是input("Left or right? ").lower()。

修正方案

将后续所有逻辑嵌套进第一个else分支,确保只有用户选择left时才会执行后续步骤,避免未定义变量的情况:

print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.") 

direction = input("Left or right? ").lower()

if direction == "right":
  print("Game over.")
else:
  swim_or_wait = input("Swim or wait? ").lower()
  if swim_or_wait == "swim":
    print("Game Over.")
  else:
    door = input("Pick a door. Red, Yellow, or Blue. ").lower()
    if door == "red" or door == "blue":
      print("Game Over")
    else:
      print("You win!")

补充说明

这种嵌套结构能保证代码的执行路径严谨:只有通过前一个分支的验证(选择left),才会进入下一个环节,所有变量都会在使用前被正确定义,不会出现未定义错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:13:17