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
๐ŸŒ
Stanford CS
cs.stanford.edu โ€บ people โ€บ nick โ€บ py โ€บ python-while.html
While Loop
While Operation: Check the boolean test expression, if it is True, run all the "body" lines inside the loop from top to bottom. Then loop back to the top, check the test again, and so on. When the test is False, exit the loop, running continues on the first line after the body lines.
๐ŸŒ
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 - 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...
๐ŸŒ
TOOLSQA
toolsqa.com โ€บ python โ€บ python-while-loop
Python While Loop | While True and While Else in Python || ToolsQA
The while loop in python is a way to run a code block until the condition returns true repeatedly. Unlike the "for" loop in python, the while loop does not initialize or increment the variable value automatically.
๐ŸŒ
Real Python
realpython.com โ€บ python-while-loop
Python while Loops: Repeating Tasks Conditionally โ€“ Real Python
March 3, 2025 - The basic syntax of a while loop is shown below: ... In this syntax, condition is an expression that the loop evaluates for its truth value. If the condition is true, then the loop body runs.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ help understand while true/while false
r/learnpython on Reddit: Help understand while True/while False
November 27, 2013 -

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!

๐ŸŒ
Wikiversity
en.wikiversity.org โ€บ wiki โ€บ Python_Concepts โ€บ While_Statement
Python Concepts/While Statement - Wikiversity
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 ...
Find elsewhere
๐ŸŒ
Board Infinity
boardinfinity.com โ€บ blog โ€บ use-while-true-in-python
Use While True in Python | Board Infinity
August 13, 2025 - This is typically done using a Boolean variable initially set to "True," then modified within the loop to become "False". Here is an example of a basic "while True" loop in Python:
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ sorry to ask such a silly question but what does 'while true:' actually mean?
r/learnpython on Reddit: sorry to ask such a silly question but what does 'while True:' actually mean?
November 14, 2023 -

what does the True refer to?

eg if i write:

while True: 
    print("hi")

i know that "hi" will be repeated infinitely, but what is it thats True thats making "hi" get printed?

also, whatever it is thats True, im assuming its always true, so is that why if i typed 'while False', none of the code below would ever run?

sorry if this is a stupid question

edit: also, besides adding an if statement, is there anything else that would break this infinite while loop?

and how would i break the loop, lets say after "hi" has been printed 10 times, using an if statement or whatever else there is that can break it. thanks!

๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can someone explain what this `while true` function is actually checking?
r/learnpython on Reddit: Can someone explain what this `while True` function is actually checking?
December 13, 2023 -

https://pastebin.com/NWkKQc1P

It's from Automate the Boring Stuff. I tried running it through the python tutor and it didn't clarify. Is the basic point that there actually isn't anything it's checking to be True, so it's an infinite loop until you trigger the `break`?

PS I figure this is something simple from much earlier that I didn't internalize. I plan to go through all the basic curriculum again to make sure there aren't any gaps in super basic knowledge.

Top answer
1 of 8
23
A while loop runs while a condition is true. True is always true, so it will run until something causes it to break (e.g. a break statement, program crash, etc.) For comparison, the first loop in the code you posted could be rewritten without an infinite loop as: age = input("Enter your age: ") while not age.isdecimal(): age = input("Please enter a number for your age: ")
2 of 8
9
Correct; this is just a way to start an infinite loop that you intend to break with some condition/break statement later on. Mostly used for starting/running an application that you don't want to close down without user intent (clicking an exit/quit button in a UI or entering "quit", "exit", etc from the command line. It *isn't* a great construct to use when you want something that has solidly defined criteria to repeat until those criteria are met. As mopslik pointed out, you would be better served in those examples to actually use the defined criteria in those as your loop conditions since you're not at risk of just sticking the user in an infinite loop if you forget to write your break statement somewhere. You, also, don't have to write so many lines to accomplish the same goal. ``` password = "" while not password.isalnum(): password = input('Select a new password (alphanumeric only') print("Password is good") ``` You do not have to print a line and then call input(), either. Just put the message you want displayed into the parens for the function call: input("Enter your age: ")
๐ŸŒ
Python
wiki.python.org โ€บ moin โ€บ WhileLoop
While loops - Python Wiki
If the condition is initially false, the loop body will not be executed at all. As the for loop in Python is so powerful, while is rarely used, except in cases where a user's input is required*, for example: n = raw_input("Please enter 'hello':") while n.strip() != 'hello': n = raw_input("Please enter 'hello':") However, the problem with the above code is that it's wasteful. In fact, what you will see a lot of in Python is the following: while True: n = raw_input("Please enter 'hello':") if n.strip() == 'hello': break
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 54226698 โ€บ while-loops-in-python-3-and-true-false-conditions
While loops in Python 3 and True/False conditions - Stack Overflow
The condition True causes the loop to continue infinitely since it can only ever evaluate to True, while False causes the loop to immediately exit without running the code in its block.
๐ŸŒ
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.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can you break a while loop via return boolean value from a function?
r/learnpython on Reddit: Can You Break A While Loop Via Return Boolean Value From A Function?
May 21, 2022 -

I feel like it should work, but Python doesn't seem to care about my feelings. So I'm playing around with functions and I feel like I should be able to create a function that returns a boolean value that breaks a while loop in the body of the code. So here's what I've got, sadly, it doesn't seem to actually read what's being returned and just continues to ask for a username. Please, ignore my stupid usernames, I am neither smart no clever. :

def username_checker(username, users,):
    """Checks list of users to find out if username is already taken"""
    if username in users:
        print("\nSorry that name is already taken.")
        return True

    else:
        print (f"\nWelcome, {username}")
        return False
        

users = ["bbrad", "poopinajimmyhat7", "coolkid28",]
while True:
    user_name = input ("\nPlease enter a username: ")
    username_checker (user_name, users)
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ python-while-loop-tutorial
Python While Loop Tutorial โ€“ While True Syntax Examples and Infinite Loops
November 13, 2020 - Iteration 2: now the value of i is 5, so the condition i < 8 evaluates to True. The body of the loop runs, the value of i is printed (5) and this value i is incremented by 1. The loop starts again. Iterations 3 and 4: The same process is repeated for the third and fourth iterations, so the integers 6 and 7 are printed. Before starting the fifth iteration, the value of i is 8. Now the while loop condition i < 8 evaluates to False and the loop stops immediately.
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ MoreAboutIteration โ€บ ThewhileStatement.html
14.2. The while Statement โ€” Foundations of Python Programming
If the condition is False, exit the while statement and continue execution at the next statement. If the condition is True, execute each of the statements in the body and then go back to step 1. The body consists of all of the statements below the header with the same indentation.
๐ŸŒ
Kansas State University
textbooks.cs.ksu.edu โ€บ intro-python โ€บ 05-loops โ€บ 02-while-loops
While Loops :: Introduction to Python
June 27, 2024 - A while loop uses a Boolean expression, and will repeat the code inside of the loop as long as the Boolean expression evaluates to True. These loops are typically used when we want to repeat some steps, but we arenโ€™t sure exactly how many times it must be done.