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')```

First, you set started to False.

Then, the else: block sets started to True.

started is now True. You never set it to False again, so it remains True.

2 Likes

thank you very much

1 Like

Try this:

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

Execution session:

enter : larch
enter : start
car started
enter : start
car already started
enter : 

Note that you have an infinite loop. Adding a condition with a break statement can remedy that.