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

Python中如何退出循环?学生开发文字冒险游戏遇while循环无法退出问题

问题原因
  • 你编写的while循环条件存在逻辑错误:Python中单独的非空字符串会被判定为布尔值True,你写的playerchoice != "wake" or "remain asleep" 等价于 (playerchoice != "wake") or True,因此无论用户输入任何内容,整个循环条件永远成立,程序会进入死循环无法正常退出。
  • 原逻辑中你想表达的是「当用户输入既不是wake也不是remain asleep时继续循环」,对应逻辑运算符应该用and而不是or。
修正方案

两种实现方式可选,第二种可读性更高:

  1. 修正逻辑运算符和判断条件
playerchoice = ""
# 两个不等判断用and连接
while playerchoice != "wake" and playerchoice != "remain asleep":
       playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
       if playerchoice == "wake":
              print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
       elif playerchoice == "remain asleep":
              print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
       else:
              print ("Please type a valid answer.") 
  1. 使用not in简化判断
playerchoice = ""
# 直接判断输入是否不在合法选项集合中
while playerchoice not in ("wake", "remain asleep"):
       playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ")
       if playerchoice == "wake":
              print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'")
       elif playerchoice == "remain asleep":
              print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'")
       else:
              print ("Please type a valid answer.") 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:39:05