-2

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

I attached pic of the output

while True:
    word = input('enter : ')
    if word == 'start':
        if started:
            print('car already started')
        else :
            started = True
            print('car started')
Archana David
  • 1,354
  • 2
  • 15
  • 26
Simo
  • 1

1 Answers1

0

You didn't show where you create the variable "started". Then, I will assume that it is None or False, that is the reason it goes first in the "else" statement.

When you do "if variable", Python will check if that variable is True. Python considers as False those values: False, None, 0, []. So, anything different from those values will return True and it will enter in your if statement.

[] = Empty list. You can consider any empty object, like dictionary.

Alfredo Miranda
  • 108
  • 3
  • 8