Jay
Jay

Reputation: 33

Need help to understand a peice of while loop code?

I am learning Python online on YouTube. And I have came across a piece of code that is confusing me. I would really appreciate if someone could help me out. Here is the code:

command = ""
started = False

while True:
    command = input("> ").lower()
    if command == "start":
        if started:
            print("car already started")
        else:
            started = True
            print("car started")

What I didn't understand is how does Python execute double ifs? And how does it know it is already executed once and if typed start again it would give me another message. Any help would highly appreciated.

Upvotes: 3

Views: 87

Answers (2)

glhr
glhr

Reputation: 4537

Here's an attempt to "transcribe" the code in English:

  1. car has not started, no command received yet
  2. start an infinite loop (meaning that the steps below will repeat forever, until you terminate/exit the program)
  3. take a command from the user, turn it into lowercase, and store it
  4. check the command entered by the user. If the command is "start", then check whether the car has started, and start it if it hasn't been already, then go back to step 3. If the user input is not "start", then don't check anything and return directly to step 3.

Upvotes: 1

KYDronePilot
KYDronePilot

Reputation: 545

The ifs are nested. The second if and else are only checked if the first condition is true. This is apparent, since they are indented after the first if.

The first if checks if the command is to start. If it is, then it checks if the car has already been started. If it has, there is no need to start it again. If not, then it starts the car.

Upvotes: 3

Related Questions