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

Python中if语句调用.lower未生效导致输入匹配失败问题咨询

错误原因

你代码中所有调用字符串小写转换方法的位置都漏写了方法调用必需的括号():

  • 字符串的lower是内置方法,必须写成lower()执行调用后,才能得到转换为全小写的字符串结果
  • 你写的choice1.lower是直接引用方法对象本身,用它和字符串"window"做相等判断永远不会成立,所以第一个if分支直接不触发,进入了最外层的else分支。
修正方案

把代码中所有的.lower替换为.lower()即可,修正后的完整代码如下:

choice1 = input('You are in front of the house, which way do you want to enter? Type "front door" or "window" and hit Enter \n')
if choice1.lower() == "window":
    choice2 = input('You snuck in through a window. You come to the foyer and can take the staircase upstairs or down to the basement. Type "basement" or "upstairs" and hit Enter to proceed \n')
    if choice2.lower() == "upstairs":
        choice3 = input("You go upstairs and are in a hallway with 3 doors to enter: 1 red, 1 green, 1 blue. Which color door do you choose? \n")
        if choice3.lower() == "red":
            print("The room is full of poisonous snakes! Game over.")
        elif choice3.lower() == "green":
            print("You found the lost trick-or-treaters and lead them out of the haunted house to safety. You win!")
        elif choice3.lower() == "blue":
            print("You ended up in a warewolf's room. It eats you! Game over.")
        else:
            print("This door doesn't exist... Game over.")
    else:
        print("You encountered a witch who cast a spell turning you into a rat! Game Over.")
else:
    print("You fell into a spike pit as you entered the house! Game Over.")

中文翻译版本代码:

choice1 = input('你现在在房子门口,你想怎么进去?输入 "前门" 或者 "窗户" 后按回车 \n')
if choice1.lower() == "窗户":
    choice2 = input('你从窗户溜了进去。你到了门厅,可以走楼梯上楼或者下楼去地下室。输入 "地下室" 或者 "楼上" 后按回车继续 \n')
    if choice2.lower() == "楼上":
        choice3 = input("你上了楼,走到了有三扇门的走廊:1扇红门、1扇绿门、1扇蓝门。你要选哪个颜色的门?\n")
        if choice3.lower() == "红色":
            print("房间里全是毒蛇!游戏结束。")
        elif choice3.lower() == "绿色":
            print("你找到了迷路的小孩,把他们带出了鬼屋到了安全的地方。你赢了!")
        elif choice3.lower() == "蓝色":
            print("你进到了狼人的房间。它把你吃了!游戏结束。")
        else:
            print("这扇门不存在...游戏结束。")
    else:
        print("你遇到了女巫,她施法把你变成了老鼠!游戏结束。")
else:
    print("你进房子的时候掉进了尖刺陷阱!游戏结束。")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:21:01