Can someone help me to understand this python code? Why doesn't this program executes only True statement?

74 views Asked by At

I am a beginner in python programming. This is regarding if condition. I wanted to write a simple program which start the car's engine (just an imaginary program). Then I wrote the code below.

According to the program, when I input firstly start, it runs True statement Car started . Then, when I input start secondly, it runs False statement Car already started. And then program stopped in the break point. What is my question here is that I want to understand this code how it executes.

Because to my understanding, when I input the first time and then the second time, program should run only the True statement (Car started). But when I input the first time, program runs the True statement (Car started) and then when I input second time, program runs the False statement (Car already started). Then It breaks the while loop. So, why doesn't program runs the True statement in both times. I want to understand this code.

command = ''
started = False
while True:
    command = input('> ').lower()
    if command == 'start':
        if started:
            print('Car already started')
            break
        else:
            started = True
            print('Car started')

I tried to understand this code.

1

There are 1 answers

0
DuckyPolice On

At the first part of the program, you run

started = False

and so, the first input, it will run the "else" statement because "started" is not equal to True. inside the "else" statement, you make it so "started" is now "True". so, the second input will run the "if" statement and not the "else" statement because the "if" statement is returning "True".