0

I'm new to coding so I've been doing exercises. This one is about a car that the user commands to start and stop. My question is that why did the given solution include the first line in the following code?:

command = ""
started = False
while True:
    command = input("> ").lower()
    if command == "start":
        if started:
            print("The car has already started")
        else:
            started = True
            print("The car started")
    elif command == "stop":
        if not started:
            print("The car has already stopped")
        else:
            started = False
            print("The car stopped")
    elif command == "quit":
        print("Goodbye!")
        break
    elif command == "help":
        print("""start - start the car
stop - stop the car
quit- quit the game""")
    else:
        print("Sorry, I don't understand")

I tried removing the first line and running the code and as far as I could tell it worked perfectly. If I'm missing something obvious I apologize!

bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • 4
    Nope. Just superstition. MAYBE they started out saying `while command != 'quit':` instead of the infinite loop. – Tim Roberts Nov 17 '22 at 07:19
  • 2
    no use if this is the whole code, otherwise this object can be used after `while` code block – sahasrara62 Nov 17 '22 at 07:20
  • 1
    Short answer: This is python and you don't need to instantiate a string the way its done on the first line – Gautam Chettiar Nov 17 '22 at 07:23
  • 1
    @TimRoberts you are correct; they started with while command != "quit" and then removed it to prove it could be simplified. Very impressive that you could deduce that. – sebas assaf Nov 17 '22 at 07:25
  • It serves no functional purpose. In fact, if you have Python 3.10+ you don't need it at all as this pattern is well suited to match/case – DarkKnight Nov 17 '22 at 07:54

1 Answers1

1

The only reason I can see is for readability. I don't say it's a good practice, just try to guess why it has been done here.

When opening the source code everyone can see which variables will be used by the program and their type.

started has to be initialized because it has a initial state.

For command it doesn't need to be initialized but it shows that it will be used and that its type is str.

Type hints can also be used instead of assigning than assign the empty string.

command: str instead of command = ""

0x0fba
  • 1,520
  • 1
  • 1
  • 11