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

Python if/elif语句异常求助:仅首尾分支可正常执行

问题分析与解决

核心问题

你的代码中间分支无法触发的主要原因:

  • 输入内容被转为小写(question_asked = str(input(...)).lower()),但部分elif条件中用了大写的"AI"做匹配,而小写输入里不可能包含大写的"AI",导致这些条件永远不满足。
  • 最后一个elif存在缩进错误,它的缩进级别和前面的if/elif不一致,需要调整为相同缩进(通常是4个空格)才能纳入循环内的条件判断链。

修正后的代码

facts = {
    'name' : 'Artificial Intelligence',
    'short-name' : 'AI',
    'about' : '...............................',
    'year' : '1943'}

running = True

while running:
    question_asked = str(input("\nWhat would you like to know?\n")).lower()

    if "name" in question_asked \
        and "artificial intelligence" in question_asked \
        and ("abbreviated" in question_asked \
        or "short" in question_asked):

        print("The abbreviated name for " + facts['name'] + \
            " is " + facts['short-name'])

    elif "name" in question_asked \
        and "ai" in question_asked \
        and ("full" in question_asked \
        or "long" in question_asked):

        print("The full name for " + facts['short-name'] + \
            " is " + facts['name'])

    elif ("first" in question_asked \
        or "original" in question_asked)\
        and "year" in question_asked \
        and ("ai" in question_asked \
        or "artificial intelligence" in question_asked):

        print(facts['short-name'] +  " was first widely recognised in " + \
            facts['year'])

    elif "about" in question_asked \
        and ("ai" in question_asked \
        or "artificial intelligence" in question_asked):

        print(facts['about'])

    elif "end" in question_asked \
        or "exit" in question_asked \
        or "quit" in question_asked \
        or 'q' in question_asked \
        or len(question_asked) == 0:

        running = False

    else:
        print("I have no knowledge or I'm not sure what you mean.")

修改说明

  1. 把所有条件中的大写"AI"替换为小写"ai",确保和转换后的输入内容匹配。
  2. 调整最后一个elif的缩进,让它和前面的if/elif保持一致,确保它属于while循环内的条件判断链。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:45:43