我正在制作一个汽车游戏。 只有“开始”、“停止”、“退出”命令。 无法识别任何其他命令
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条件不满足
您在循环的顶部获得输入,因此它在检查循环条件之前完成完整的循环迭代
一个选项是将输入提取移动到循环的末尾,以便下一步要检查循环条件。您还可以通过在使用
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"
所以
执行,因此您的输出成为
查看您的代码,您会得到“quit”输入,然后返回到first if(不正确)——>;下一个elif(不正确)——>;下一步(正确)——>;打印(“车辆停止”)->;下一个while(不正确)——>;完成循环并转到“我不明白”
如下更改代码:
相关问题 更多 >
编程相关推荐