How booleans work with if statements in Python?

hi Guys I just want to know how Booleans work with “if” statements because it has caused some confusing and I want to understand the logic behind it and I believe that many other beginners have the same confusing. here I have an example of a car game which runs perfectly fine but I want to understand how it works :

in the below code I want to understand why when I enter “start” the Else statement gets executed FIRST and when I enter “start” AGAIN and AGAIN the If statement keeps getting executed and not the Else statement

started = False
while True:
    word = input('enter : ')
    if word == 'start':
        if started:
            print('car already started')
        else :
            started = True
            print('car started')

Whatever code inside if runs when the condition you passed to it resolves to True. Otherwise, the code inside else runs.

At the start of the loop, your started is always False. It only ever changes when it reaches the else block. After reaching the else block, it is always True. Because you never change it to something else.

That’s why when you initially start the car, you see “car started” message and afterwards you see “car already started” message.

1 Like