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

Python添加elif后else语句失效,循环被错误终止求因

问题分析与解决方案

嘿,我一眼就瞅到问题出在哪儿啦!你的elif条件写得有逻辑错误,导致程序直接跳过了else分支~

错误原因

你看这段代码:

elif user_input7 == "Hollow Knight" or "hollow knight" or "Hollow knight":

在Python里,or是逻辑或运算符,它会逐个判断条件。这里的问题是,"hollow knight"和"Hollow knight"是单独的非空字符串,而非空字符串在布尔判断里会被视为True。也就是说,不管用户输入什么,只要前面的if和第一个elif不匹配,这个elif的条件都会成立(因为后面两个字符串永远是True),所以程序直接执行break终止循环,完全轮不到else分支。

修正方案

有几种简单的修正方式,选你喜欢的就行:

  1. 完整的多条件判断
    每个选项都和user_input7做比较:

    elif user_input7 == "Hollow Knight" or user_input7 == "hollow knight" or user_input7 == "Hollow knight":
    
  2. 用集合判断(更简洁)
    把所有正确答案放进集合,用in判断:

    elif user_input7 in {"Hollow Knight", "hollow knight", "Hollow knight"}:
    
  3. 统一转小写判断(最灵活,能覆盖所有大小写组合)
    把用户输入转成小写,再和统一小写的答案比较,这样不管用户输入HOLLOW KNIGHT还是hOllOw KnIgHt都能匹配:

    elif user_input7.lower() == "hollow knight":
    

修正后的完整代码

这里给你用第三种方案的完整代码,更实用:

user_input7 = input("What is my favorite game?")
while True:
    if user_input7 == "Hint" or user_input7 == "hint":
        print("The first two letters of the first word start with ho.")
        user_input7 = input("What's my favorite game?")
        continue
    elif user_input7 == "idk" or user_input7 == "i dont know":
        print("uh if you don't know it type hint")
        user_input7 = input("What's my favorite game?")
        continue
    elif user_input7.lower() == "hollow knight":
        print("About time you got that one")
        break
    else:
        print("Why isn't this working")

这样修改后,程序就会正常进入else分支啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:47:52