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

使用while循环与if语句开发简易文本游戏时输入功能异常的问题求助

问题分析与修复方案

嘿,我一眼就瞅出问题所在啦!你遇到的情况大概率是输入内容的前后空白字符在搞鬼——当你用input()获取用户输入时,哪怕只是不小心多敲了个空格(比如输入left而不是left),这个带空格的字符串和你判断的"left"/"right"就完全不相等了,但直接赋值的时候你写的是精确的字符串,所以能正常匹配。

具体修复步骤

给你的input()结果加上.strip()方法,它会自动去掉字符串前后的所有空白(包括空格、换行符这些),另外还可以加上.lower()来兼容大小写输入(比如用户输入Left也能正常识别),完美解决输入不匹配的问题。

修复后的完整代码

choice = input("you are now in a forest, please pick a direction(left or right)").strip().lower()
while choice == "right":
    print("a strange wind had sent you back to forest")
    choice = input("you are now in a forest, please pick a direction(left or right)").strip().lower()
if choice == "left":
    print("u saw a cave, in or not?")
    choice = input("type in or not ").strip().lower()
    if choice == "in" :
        print("u saw a bear claw and that's the last view in your eyes")
    elif choice == "not":
        print("after two and a half hours walking, you are now out of the forest")

额外小提示

  • input()函数本身返回的就是字符串类型,所以不需要额外用str()转换哦,去掉str()能让代码更简洁。
  • 加上.lower()后,不管用户输入LEFT、Right还是left,都能正确匹配判断条件,游戏体验会更好~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 16:47:37