Use break to exit a loop:

while True:
    ser = serial.Serial("/dev/ttyUSB0", 4800, timeout =1)
    checking = ser.readline();
    if checking.find(",,,,"):
        print "not locked yet"
    else:
        print "locked and loaded"
        break

The True and False line didn't do anything in your code; they are just referencing the built-in boolean values without assigning them anywhere.

Answer from Martijn Pieters on Stack Overflow
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ trouble understanding while not
r/learnpython on Reddit: Trouble understanding While Not
February 16, 2017 -

I'm doing "automate the boring stuff" and was on an early lesson about while loops. I can't wrap my head around "while not." The code is below

name = ''
while not name:
     print('Enter your name:')
     name = input()
print('How many guests will you have?')

While my limited knowledge, I would write it instead as

name = ''
while name == '':
    print('Enter your name:')
    name = input()
print('How many guests will you have?')

My question is how can they mean the same thing? Both start with name = False/empty. The way I interpret the top code is, while name is not False/empty. The way I interpret the bottom is, while name is equal to False/empty. In my mind, the top would keep looping with any True value. Thanks for your help!

EDIT: formatting

EDIT 2: Finally figured it out. I'm posting this edit for prosperity sake, for any other programming ogres like me. As long as the condition line is True, the loop will run. If the condition is False, the loop will not run. Even though name is False, the condition line is True and the loop will go until something is inputted. Once something is typed in, name becomes True, which would make the condition not name False, ending the loop.

Thanks everyone for helping me understand that! It's so simple now that I see it. I'm super new to Python and made a rookie mistake.

๐ŸŒ
Wikiversity
en.wikiversity.org โ€บ wiki โ€บ Python_Concepts โ€บ While_Statement
Python Concepts/While Statement - Wikiversity
April 28, 2024 - Although the if statement from the previous lesson can serve many purposes, it isn't good at being recursive. This means that the said statement cannot loop over and over again. This is where the while statement comes into play. This statement will execute its code block over and over again ...
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do while not loops work
r/learnpython on Reddit: How do while not loops work
September 11, 2024 -

I was reading through this code and I'm just not getting how while loops work when not operator is also used.

https://pastebin.com/5mfBhQSb

I thought the not operator just inversed whatever the value was but I just can't see this code working if that's the case.

For example , the while not sequenceCorrect should turn the original value of False to True, so the loop should run while it's True. But why not just state while True then? And why declare sequenceCorrect = True again? Doesn't it just means while True, make it True? And so on.

The only way it makes sense to me is of the while not loop always means False (just like the while always means as long as it's True) even if the value is supposed be False and should be inverted to True.

So, is that the case? Can anyone explain why it works like that?

Top answer
1 of 8
7
In general, recall the while loop syntax. while : Conceptually, coding aside, consider filling a glass of water. Is there space for more water in the glass? Okay, then pour some. Without going in detail of how this funky glass object is defined, hopefully the following makes sense as a python analog of that process. while glass.has_space(): #we're still filling the glass glass.add_water() #glass is now full of water Without writing out how this glass object works, let's say it has another method for returning a boolean (True/False) for whether or not it is currently full, instead of the previous example of whether or not it had space for more water. We can fill the glass in the same way, but we have to negate that statement using the not operator while not glass.is_full(): #we're still filling the glass glass.add_water() #glass is now full of water Going back to the initial syntax, which is still the same, the only thing we've done is changing the condition statement of the loop. Instead of checking that glass.has_space() evaluates to True, we are now checking that the expression not glass.is_full() evaluates to True. That is the same statement as evaluating that glass.is_full() evaluates to False, because the only thing the not operator does to a boolean is negating it, i.e. True becomes False and vice versa. Now looking at your code linked, the condition for looping is that not sequenceCorrect evaluates to True, which is equivalent to the statement that sequenceCorrect is False. I won't paste the code here, but we see on line 3 that sequenceCorrect starts its life being False, so upon entering the while loop we do indeed step into that block of code because at that time not sequenceCorrect is in fact True. Then the first thing we do on line 5 is reassign it to True. If the remaining lines don't change it back to False, this will stop the while loop from repeating, since in this current state not sequenceCorrect evaluates to False. So you can say that line 5 is defaulting the loop to not going to be repeated. The only way for the loop to be repeated is for lines 6-8 with the nested for loop and if statement to find some character in dna that is not in "actgn", upon which sequenceCorrect will be assigned to False and thus the statement in the while loop not sequenceCorrect would evaluate to True and thus the loop would repeat itself once more. Personally, I think this is just a pretty unclear way to achieve the goal of checking the validity of that input string. I would have defined it another way, but I can't see anything wrong with it really. If the not operation in the while loop statement is bothering you, you could equally have rewritten the code with a variable for instance named sequenceIncorrect and just flipped all assignments i.e. True's become False's and vice versa.
2 of 8
2
The difference here is that by using not sequenceCorrect you are avoiding the use of the break keyword. It's cleaner and makes the loop terminate itself, rather than relying on a specific keyword and force terminate it. You could use while True, but that way is not descriptive enough and can potentially create and endless loop if you don't take care of the edge cases. Think about it: while not sequenceCorrect is telling you, without a single comment line, that the loop should run while sequenceCorrect is False, vs while True which the only thing that's telling you is that this loop will run endlessly for unknown reasons.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ help understand while true/while false
r/learnpython on Reddit: Help understand while True/while False
December 19, 2015 -

for example, why does this code work:

user = input("Enter marital status: ")
user = user.upper()
valid = False
while not valid:
    if user == "M" or user == "S":
        valid = True
    else:
        print ("invalid input")
        user = input("Enter marital status: ")
        user = user.upper()

but this doesn't:

user = input("Enter marital status: ")
user = user.upper()
valid = True
while not valid:
    if user == "M" or user == "S":
        valid = False
    else:
        print ("invalid input")
        user = input("Enter marital status: ")
        user = user.upper()

isn't the boolean condition changing in both cases?

can someone just give me some guidelines for using while True/False,e.g. when is it best to use this type of a while loop? that I can follow on my test tomorrow (yes, tomorrow).

Thanks in advance!

Find elsewhere
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-while.html
While Loop
With a while-loop, it's possible to accidentally write a loop that never exits. In that case, the while just loops and loops but never makes the test False to exit.
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ not-in-while-loops
Using not in Boolean while Loops (Video) โ€“ Real Python
00:32 So you can use a while loop using a not condition to ensure that this happens. Hereโ€™s a simple example. The player is supposed to enter a name at the input() statement. 00:44 This action will repeat until the player types something at the prompt. Remember the empty string ("") has a truth value of False, so not name will return True if name is still empty.
Published ย  July 19, 2022
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ WhileLoop
While loops - Python Wiki
Using 1 was minutely faster, since True was not a keyword and might have been given a different value, which the interpreter had to look up, as opposed to loading a constant. As a programmer, it is up to you which style to use - but always remember that readability is important, and that while speed is also important, readability trumps it except in cases where timings are significantly different. Starting in Python 3, True, False, and None are keywords, so using while 1 no longer provides the tiny performance benefit used to justify it in earlier versions.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ while-loops-in-python-while-true-loop-statement-example
While Loops in Python โ€“ While True Loop Statement Example
July 19, 2022 - The general syntax for writing a while loop in Python looks like this: while condition: body of while loop containing code that does something ... You start the while loop by using the while keyword. Then, you add a condition which will be a Boolean expression. A Boolean expression is an expression that evaluates to either True or False...
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ what is โ€œnot trueโ€ in python?
What is "not True" in Python? - AskPython
February 27, 2022 - This example is alone sufficient to prove how โ€œnotโ€ is useful: ... The code will not run. The while loop iterates the code if and only if the condition inside its parenthesis is True. Here the condition is not True means it is False...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_while_loops.asp
Python While Loops
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... With the while loop we can execute a set of statements as long as a condition is true. ... Note: remember to increment i, or else the loop will continue forever.
Top answer
1 of 2
5

Since your while not pair: loop did not work, you have found an important difference: pair == False only tests true if pair is set to 0 or False (the only two values that test as equal to False), while while not pair tests for any truth value (inverting that value).

You appear to have assigned some other value to pair that is neither of those two values causing the behaviour to change (a truthy value to break out early, or a falsey value to keep the loop going longer than expected).

It is that difference that is one of the reasons why the Python style guide recommends you always use if true_expression or if not false_expression rather than use == True or == False:

  • Don't compare boolean values to True or False using ==.

    Yes: if greeting:
    No: if greeting == True:
    Worse: if greeting is True:

Last but not least, for a while ...: loop that simply tests against a single boolean flag (while flag: or while not pair:), consider using while True: and break instead. So rather than do:

flag = True
while flag:
    # ...
    if condition:
        flag = False

do this instead:

while True:
    # ...
    if condition:
        break
2 of 2
0

Aside from actually having little or no difference at all,

Using False in a == comparison allows usage of 0 and 1.

0 == False
1 == True

Using not is inversion of current value.

not 0 == True
not 1 == False
not False == True

You can use in your program assuming that pair can only contain boolean values:

while not pair:

If you however still want to use a variable that can contain both boolean and number, you can use:

while pair is False:
๐ŸŒ
IONOS
ionos.com โ€บ digital guide โ€บ websites โ€บ web development โ€บ python while loop
How to use while loops in Python - IONOS
September 26, 2022 - word = 'Python' letters = iter(word) letter = '' while letter is not None: letter = next(letters, None) if letter: print(letter) Python while loops are especially interesting because they can be used to implement infinite loops. At first glance this might seem counterintuitive, as programmers fear accidental infinite loops. Thatโ€™s because the condition never becomes false, so the program gets stuck:
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 65293083 โ€บ how-to-properly-use-while-not-loops-in-python
How to properly use "while not" loops in python? - Stack Overflow
The best explanation for while not guessed is that it is essentially saying "while guessed is not equal to true". This is to say it is basically "while guessed is false." So the while loop will run for as long as guessed is false and tries > 0.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ how-to-use-while-true-in-python
How to use while True in Python - GeeksforGeeks
May 27, 2025 - In Python, loops allow you to repeat code blocks. The while loop runs as long as a given condition is true. Using while True creates an infinite loop that runs endlessly until stopped by a break statement or an external interruption.