Python Forum

Full Version: Python code: While loop with if statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Dear Friend,
I am a beginner in python.
I find it hard to understand the logic of the following issues:
1- why we use empty string?
2-Why when you right "start" for the second time you get "car already-started"

Your help will be appreciated.

Note: It is a code for a game. the code is long but I have selected the section that I did not understand.

command = "" 
already_started = False
while command != "quit":
   command = input(">").lower()
   if command == "start":
        if already_started:
            print("car already started")
        else:
            already_started = True
            print("car already started")
            print("car started")
Output:
>start car started >start car already started
Your questions have nothing to do Python. They are questions about the program logic. Program logic can be arbitrary. Everything here is a guess.

1. What value do you think should be used to initialize command?

The loop is designed to run until the user enters "quit". When command == 'quit' the loop stops running. The comparison in line 3 requires that a variable named "command" has been created. Variables are created by assigning a value to a name, so there has to be a value assigned to command before the loop. It could be almost any value. It could be None, or 2 or "Hello". The only thing you cannot do is set command = "quit" because the loop would not run.

2. The code you posted is not the code you ran to get the output

The code prints "car already started" regardless of the value of "already started". I think the code was written like this:
        if already_started:
            print("car already started")
        else:
            already_started = True
            print("car started")
This is the code I will use to answer the question.

I don't know. I do not know why the author of the code wants the program to print "car already started" if you enter "start" after you have already started the car. The program uses already_started to remember that you had entered "start" sometime in the past. When you enter "start" it checks if the car was already_started and prints "car already started" if already_started is True, else it prints "car started" and assigns alreadhy_started = True to remember that the car was started.