jeudi 4 février 2021

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

I want to ask a question about a boolean question inside the loop.

Let me first explain this: if I Input help, then it will show me

start - to start the car,

stop - to stop the car,

quit- to exit,

If I Input start, stop, quit it will print above individually.

If I Input start and stop again it will show ("the car is already started") or ("the car is already stopped").

please see the code below:

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")

My question is how do python find out if I already typed start or stop, which will print ("the car is already started") or ("the car is already stopped"). The boolean started which is defined as False at the beginning seems to be the answer in this loop, but I don't understand the logic behind this.

Thank you so much all for your help and support, really appreciate it.

Aucun commentaire:

Enregistrer un commentaire