Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

python - 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.

question from:https://stackoverflow.com/questions/66047106/struggle-to-understand-the-logic-behind-the-booleans-inside-the-while-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...