努力理解 while 循环中布尔值背后的逻辑

时间:2021-02-04 13:57:04

标签: python if-statement while-loop boolean boolean-logic

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

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

start - 启动汽车,

stop - 停止汽车,

quit- 退出,

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

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

请看下面的代码:

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 的布尔值 started 似乎是这个循环中的答案,但我不明白这背后的逻辑。

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

0 个答案:

没有答案