难以理解 while 循环中布尔值背后的逻辑

Struggle to understand the logic behind the booleans inside the while loop

提问人:Data Beginner 提问时间:2/4/2021 更新时间:2/4/2021 访问量:53

问:

我想问一个关于循环内布尔问题的问题。

让我先解释一下: 如果我输入帮助,那么它会向我显示

启动 - 启动汽车,

停止 - 停止汽车,

退出-退出,

如果我输入开始、停止、退出,它将单独打印在上面。

如果我输入再次启动和停止,它将显示(“汽车已经启动”)或(“汽车已经停止”)。

请看下面的代码:

command = ""

started = False

while True:
    command = input("> ").lower()
    if command == "start":
        if started: 
            print("the car is already started")
        else:
            started = True 
            print("start the car")
    elif command == "stop":
        if not started: 
            print("the car is already stopped")
        else:
            started = False 
            print("stop the car")
    elif command == "help":
        print("""
start - to start the car
stop - to stop the car
quit- to exit
                """)
    elif command == "exit":
        print("exit the game")
        break
else:
    print("don't understand")

我的问题是python如何确定我是否已经输入了start或stop,这将打印(“汽车已经启动”)或(“汽车已经停止”)。 开头定义为 False 的布尔开始似乎是这个循环中的答案,但我不明白这背后的逻辑。

非常感谢大家的帮助和支持,非常感谢。

python if-statement while-loop 布尔 逻辑

评论

1赞 Scott Hunter 2/4/2021
这将是学习如何使用调试器的好时机,这样你就可以看到这个变量在程序执行过程中会发生什么。
1赞 Abdul Aziz Barkat 2/4/2021
if started这意味着,如果启动的变量为 True(或 Truey),则执行以下命令。
2赞 Suuuehgi 2/4/2021
started跟踪(汽车的)状态。 是 or 的简写,否定也是如此。您无法启动启动的汽车,因此您需要以某种方式跟踪状态。if startedif started == Trueif started is True
0赞 Data Beginner 2/4/2021
谢谢,我现在想通了。

答: 暂无答案