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

为何Python代码中else分支始终触发,即便上方if条件成立?

问题原因

你这段代码里的所有if都是独立判断——哪怕前面的stop/start/help条件已经匹配,程序还是会继续执行到最后一个if command.lower() == 'quit'的判断。只要输入的不是quit,就必然触发它的else分支,所以不管输入什么合法指令,都会弹出那句不懂的提示。

修复方案

把前面的独立if改成elif,形成完整的条件判断链,这样只要有一个条件匹配,后面的判断就会直接跳过,不会再执行到最后的else:

car_state = 'stopped'
game_on = True


while game_on:
    command = input('> ')
    if command.lower() == 'stop':
        if car_state == 'stopped':
            print('The car is already not running')
        else:
            print('The car halts to a stop')
            car_state = 'stopped'

    elif command.lower() == 'start':
        if car_state == 'stopped':
            print('The car starts vroom')
            car_state = 'running'
        else:
            print('The car is already running')

    elif command.lower() == 'help':
        print('''
               start
               stop
               help
               quit

               ''')
    elif command.lower() == 'quit':
        game_on = False
    else:
        print('I dont understand that. Type help for commands')

修改后,只有当输入的指令不匹配stop/start/help/quit中的任何一个时,才会触发最后的提示语句。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:52:01