为何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
相关产品推荐
相关产品推荐

