Python在循环时执行,即使条件不满足?

2024-09-29 05:15:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个汽车游戏。 只有“开始”、“停止”、“退出”命令。 无法识别任何其他命令

command = ""

while command != "quit":
    command = input("Command: ")
    if command == "start":
        print("Car ready to go")
    elif command == "stop":
        print("Car stopped")
    else:
        print("I don't understand that")
else:
    print("Game exited")

除了“退出”之外,所有命令都可以正常工作。使用while循环,它会执行和打印else语句:

I don't understand that
Game exited

命令=“quit”应该呈现while条件False,从而向前跳,只执行外部else语句。为什么它执行两个else语句,甚至认为while条件不满足


Tags: 命令gamethat语句条件car汽车else
3条回答

您在循环的顶部获得输入,因此它在检查循环条件之前完成完整的循环迭代

while command != "quit":
    command = input("Command: ")
    ...

一个选项是将输入提取移动到循环的末尾,以便下一步要检查循环条件。您还可以通过在使用break获取输入后检查quit来提前中断循环

while-else的工作方式如下:如果不满足while条件,则执行else
因此,当您在程序中键入“quit”时,if command == "start":elif command == "stop":条件不满足。
因此,执行else,打印I don't understand that

现在,再次检查while循环的条件:command != "quit"
但是,这个条件是False,因为command的值现在是"quit"

所以

else:
    print("Game exited")

执行,因此您的输出成为

I don't understand that
Game exited
while command != "quit":
    command = input("Command: ")
    if command == "start":
        print("Car ready to go")
    elif command == "stop":
        print("Car stopped")
    else:
        print("I don't understand that")
else:
    print("Game exited")

查看您的代码,您会得到“quit”输入,然后返回到first if(不正确)——>;下一个elif(不正确)——>;下一步(正确)——>;打印(“车辆停止”)->;下一个while(不正确)——>;完成循环并转到“我不明白”

如下更改代码:

while command != "quit":
    command = input("Command: ")
    if command == "start":
        print("Car ready to go")
    elif command == "stop":
        print("Car stopped")
    elif command != "quit":
        print("I don't understand that")
else:
    print("Game exited")

相关问题 更多 >