Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I break while loop by raw_input()? python 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 :)

like image 535
Shervin Rad Avatar asked Nov 17 '25 16:11

Shervin Rad


1 Answers

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' ")
like image 162
Stuart Buckingham Avatar answered Nov 20 '25 13:11

Stuart Buckingham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!