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

Python if语句运行异常:非yes输入时elif/else失效需按两次回车

故障原因

代码在每个条件判断节点都单独调用input(),执行逻辑存在缺陷:

  • 运行到if input().strip().lower() == 'yes'时,程序暂停等待第一次输入,输入为yes时匹配成功,分支正常运行
  • 若第一次输入不是yes,if判断不通过,程序走到elif分支时会再次调用input()暂停等待第二次输入,第一次输入的内容直接被丢弃,因此不会触发任何响应,必须按第二次回车才会继续执行判断
  • 若第二次输入也不是no,程序才会进入else分支,这就是非yes输入需要按两次回车才能得到反馈的根本原因
修复方案

只调用一次input()获取用户输入,将输入结果存入变量,后续所有条件判断都基于该变量的值完成,修复后的代码如下:

while current_room == 'Bathroom':
    if 'Lavender Oil,' not in inventory:
        print('Wow, this bathroom has so many bottles of stuff!')
        print('Do you want to investigate the shelf of bottles?')
        # 单次获取输入存储,避免重复等待用户输入
        user_choice = input().strip().lower()
        if user_choice == 'yes':
            print('yes')
        elif user_choice == 'no':
            print('no')
        else:
            print('else')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 21:27:20