While loops in Python are used to repeatedly execute a block of code as long as a specified condition remains True. The loop checks the condition before each iteration, and if it evaluates to True, the loop body runs; otherwise, the loop terminates.
Key Features
Condition-Based Execution: The loop continues while the condition is
True.Loop Body: Contains the statements to be repeated, indented under the
whilestatement.Infinite Loops: Can occur if the condition never becomes
False. Always ensure variables in the condition are updated inside the loop to avoid this.breakStatement: Allows early exit from the loop, even if the condition is stillTrue.elseClause: Executes once after the loop ends naturally (not viabreak).
Basic Syntax
while condition:
# Code to executeExample: Counting from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1Output:
1
2
3
4
5Common Use Cases
User Input Validation: Keep prompting until valid input is received.
Dynamic Iterations: When the number of iterations isn’t known in advance (e.g., processing data until end-of-file).
Simulating Do-While Loops: Use
while True:withbreakto ensure the loop runs at least once.
Example: Simulating a Do-While Loop
while True:
user_input = input("Enter 'quit' to exit: ").lower()
if user_input == 'quit':
break
print(f"You entered: {user_input}")Tip: Always update loop variables inside the loop body to prevent infinite loops. Use
breakandelseclauses for advanced control flow.
I am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
Or:
stuff()
while not fail_condition:
stuff()
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
Update:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
Answer from Tom on Stack OverflowI am not sure what you are trying to do. You can implement a do-while loop like this:
while True:
stuff()
if fail_condition:
break
Or:
stuff()
while not fail_condition:
stuff()
What are you doing trying to use a do while loop to print the stuff in the list? Why not just use:
for i in l:
print i
print "done"
Update:
So do you have a list of lines? And you want to keep iterating through it? How about:
for s in l:
while True:
stuff()
# use a "break" instead of s = i.next()
Does that seem like something close to what you would want? With your code example, it would be:
for s in some_list:
while True:
if state is STATE_CODE:
if "//" in s:
tokens.add( TOKEN_COMMENT, s.split( "//" )[1] )
state = STATE_COMMENT
else :
tokens.add( TOKEN_CODE, s )
if state is STATE_COMMENT:
if "//" in s:
tokens.append( TOKEN_COMMENT, s.split( "//" )[1] )
break # get next s
else:
state = STATE_CODE
# re-evaluate same line
# continues automatically
Here's a very simple way to emulate a do-while loop:
condition = True
while condition:
# loop body here
condition = test_loop_condition()
# end of loop
The key features of a do-while loop are that the loop body always executes at least once, and that the condition is evaluated at the bottom of the loop body. The control structure show here accomplishes both of these with no need for exceptions or break statements. It does introduce one extra Boolean variable.
Is it weird that I NEVER use while loops? It’s just not something I’ve felt like I needed, ever. What are some situations where using a while loop is necessary?
Help with a while loop
loops - When to use "while" or "for" in Python - Stack Overflow
Trying to get this while loop in python to do stuff.
posting wouldn't let me tab lol
More on reddit.comVideos
I’ve written a lot of python code over the last few months, but I can’t think of a single time I’ve ever used a while loop. I mean, I use for loops pretty often, but not while loops.
Is this just down to personal preference, and I’m just using what I’m comfortable with? Or can you guys think of some situations where a while loop would be the easiest way to do things, but it’s possible to do it with a for loop? Maybe I’m using for loops in situations that I should be using while loops.
EDIT: Thanks for the suggestions. I found a few places in my code where a while loop makes sense.
First, I check if a folder has any files in it, and while it does, I delete the first one in the list:
useless_files = os.listdir("MGF_HR_Data") # I think these are files it creates when downloading the MGF data but they are extra and don't do anything
while len(useless_files)>0:
os.remove(f"MGF_HR_Data/{useless_files[0]}")
useless_files = os.listdir("MGF_HR_Data")
print("Deleting useless file from MGF_HR_Data") I also used a while loop to check if the data has been downloaded, and if it hasn't prompt the user to download it and then press enter to check again. This way, the code doesn't break if the user forgot to download the file first:
# Check if you downloaded the file in Matlab already. If not, ask the user to download it and try again.
while os.path.exists(file1)==False:
print(f"{file1} not found. Please open Matlab and run the following code to download the MGF data:" )
print(f"download({wstime.year}, {wstime.month}, {wstime.day})")
input("Press enter to try again after downloading the MGF data. \n") (Okay, I know this isn't the most efficient way to do this. There must be a way to use python to open matlab and run a matlab command, rather than asking the user to do it themselves. However, I don't know how to do that, so this works for now.)
Yes, there is a huge difference between while and for.
The for statement iterates through a collection or iterable object or generator function.
The while statement simply loops until a condition is False.
It isn't preference. It's a question of what your data structures are.
Often, we represent the values we want to process as a range (an actual list), or xrange (which generates the values) (Edit: In Python 3, range is now a generator and behaves like the old xrange function. xrange has been removed from Python 3). This gives us a data structure tailor-made for the for statement.
Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.
In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted and enumerate functions apply a transformation on an iterable that fits naturally with the for statement.
If you don't have a tidy data structure to iterate through, or you don't have a generator function that drives your processing, you must use while.
while is useful in scenarios where the break condition doesn't logically depend on any kind of sequence. For example, consider unpredictable interactions:
while user_is_sleeping():
wait()
Of course, you could write an appropriate iterator to encapsulate that action and make it accessible via for – but how would that serve readability?¹
In all other cases in Python, use for (or an appropriate higher-order function which encapsulate the loop).
¹ assuming the user_is_sleeping function returns False when false, the example code could be rewritten as the following for loop:
for _ in iter(user_is_sleeping, False):
wait()