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

初学者求助:如何实现输入no时while循环继续,输入yes时程序终止?

问题分析与修正

先说说你代码里的核心问题:

  • 外层循环条件写反了:你要的是输入“yes”就停止、“no”继续循环,但原代码while leave == "yes"意味着只有当leave是yes时才会进入循环,完全和需求反过来了。
  • 内层循环结束后rn的值是0(触发rn !=0退出的条件是输入0),当你输入“no”想继续玩时,内层循环的rn !=0条件不满足,会直接再次跳到“是否离开”的提问,没法继续输入房间号。
  • 初始代码里rn = 1直接覆盖了用户第一次输入的房间号,导致第一次输入的房间白选了。
  • 另外desc列表长度比rooms少一个,输入房间号9时会触发索引越界错误。

修正后的代码:

rooms = ["Front Door", "Living Room", "Kitchen", "Study", "Storage", "Basement", "Master Bedroom", "Bathroom", "Attic", "Garden"]

# 补全desc列表,和rooms长度一致(10个元素)
desc = [
    "Was it too scary?", 
    "The TV is on, what can you find?", 
    "It smells so bad!", 
    "The Master did all his work here...", 
    "It is so dark and so cold in here... Why is it so frosty?", 
    "The Master has his secrets...", 
    "Don't worry its just a bathroom!", 
    "Rubbish and Antiques", 
    "Beautiful, is it not?",
    "The garden is full of weeds..."  # 新增对应Garden的描述
]

roomLIT = [True, True, True, True, False, False, False, False, True, False]  # 对应10个房间的灯光状态
roomLocked = []

username = input("Welcome Player! What is your username? ")
age = input("What is your age? ")

# 初始化leave为"no",让循环一开始就能运行
leave = "no"
while leave != "yes":
    rn = int(input("Enter Room Number (0-9): "))
    # 检查输入的房间号是否合法,避免索引越界
    if 0 <= rn < len(rooms):
        print(f"You have entered the {rooms[rn]}")
        print(desc[rn])
    else:
        print("Invalid room number! Please enter a number between 0 and 9.")
    # 每次输入房间后询问是否离开
    leave = input("Do you want to leave? (yes/no) ").strip().lower()

修正点说明:

  • 外层循环改成while leave != "yes",只要用户没输入yes,循环就一直运行,符合你的需求。
  • 去掉多余的内层循环,直接在每次循环里让用户输入房间号,避免rn值卡住的问题。
  • 补全desc列表,确保每个房间都有对应描述,同时添加输入合法性检查,防止无效数字报错。
  • 去掉覆盖用户初始输入的rn = 1,让流程更顺畅。
  • 对leave的输入做strip().lower()处理,避免用户输入大小写或空格导致判断出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 21:48:22