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

如何通过识别句子中的单个关键词退出while循环

实现含关键词的输入识别以退出循环

要让程序识别包含"key"的任意输入(比如"find key"、"get key")并退出循环,只需要把判断逻辑从严格匹配字符串改成检查字符串中是否包含目标关键词,同时可以忽略大小写提升用户体验。

修改后的完整代码

import time
# 补充清屏函数定义(适配不同操作系统)
def cls():
    import os
    os.system('cls' if os.name == 'nt' else 'clear')

#############Phase0#############
print("\n欢迎来到你的冒险之旅", flush=True)
time.sleep(2.1)
print("\n你的故事从这里开始", flush=True)
time.sleep(2.1)
cls()

#############Phase1#############
print("\n你发现自己身处一个黑暗的空房间")
print("\n你想做什么?")
# 示例动作列表,可根据需求调整
movesList = ["up", "look around", "find key"]
print(movesList,"\n")

prompt2 = input(' ')
while prompt2.lower() != "up":
    print("那里什么都没有\n")
    prompt2 = input('你想做什么?')    

cls()
print("你来到了门前\n")
print("但是门被锁住了......\n")
prompt3 = input(' ')
while "key" not in prompt3.lower():
    print('那样打不开门...\n')
    prompt3 = input('你想做什么:\n')
print("你打开了门锁")

print("你成功逃脱了!!!!!!!!")

关键修改说明

  • 循环条件调整:将while prompt3 != "key"改为while "key" not in prompt3.lower()
    • prompt3.lower()把输入转为小写,消除大小写敏感问题(比如"KEY"、"Find Key"都能被识别)
    • "key" not in ...检查输入字符串中是否包含"key"子串,只要输入里有这个关键词就会触发退出循环
  • 移除原代码中多余的break:原循环内的break会导致循环仅执行一次,失去循环重试的意义
  • 修正拼写错误、完成中英翻译:让交互提示更符合中文使用场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:55:21