3

I need some help understanding the differences between the following. In the first example, I want the loop to break when the user inputs False:

true = True

while true:
    print("Not broken")
    true = input("to break loop enter 'False' ")

There was a question asked at: how do I break infinite while loop with user input

Which gives this solution:

true= True

while true:
    print("Not broken")
    true = input("to break loop enter 'n' ")
    if true == "n":
        break
    else:
        continue

And I don't understand why the first method doesn't work and the second does??? Why doesn't python take the input as if someone was changing the script and change the variable "true"? Whats going on behind the scenes?

Any help would be appreciated. Thanks in advance :)

Shervin Rad
  • 460
  • 9
  • 21

1 Answers1

3

The while statement is conditional, and the user entering the String "False" will still resolve to a True outcome.

For an idea of what Python considers True and False, checkout this link: https://realpython.com/python-conditional-statements/

Building on this answer Converting from a string to boolean in Python?, the best way to check is:

true = True

while true is not 'False':
    print("Not broken")
    true = input("to break loop enter 'False' ")
Stuart Buckingham
  • 1,574
  • 16
  • 25