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 while statement.

  • Infinite Loops: Can occur if the condition never becomes False. Always ensure variables in the condition are updated inside the loop to avoid this.

  • break Statement: Allows early exit from the loop, even if the condition is still True.

  • else Clause: Executes once after the loop ends naturally (not via break).

Basic Syntax

while condition:
    # Code to execute

Example: Counting from 1 to 5

count = 1
while count <= 5:
    print(count)
    count += 1

Output:

1
2
3
4
5

Common 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: with break to 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 break and else clauses 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 Overflow
🌐
Python.org
discuss.python.org › python help
Need help understanding this while loop - Python Help - Discussions on Python.org
February 13, 2024 - I’m new to while loops, and I don’t quite get what’s going on in this code from my book: current_number = 1 while current_number <= 5: print(current_number) current_number += 1 After just watching a video on Yo…
Discussions

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?
Simplest example... Asking for user input, validating it, and asking it again if the user got it wrong, in a loop, forever, until he gets it right... For example I want only positive numbers, how would you do that with a for loop? More on reddit.com
🌐 r/learnpython
189
270
September 29, 2022
Help with a while loop
I need help fixing up this while loop. When I place my answer I end up with the same answer “That is not A, B, C, D or E, try again:” print("1. What is the smallest unit in life? -'2points'-") print("A: organs") print("… More on discuss.python.org
🌐 discuss.python.org
0
February 5, 2024
loops - When to use "while" or "for" in Python - Stack Overflow
When I should use a while loop or a for loop in Python? It looks like people prefer using a for loop (for brevity?). Is there any specific situation which I should use one or the other? Is it a mat... More on stackoverflow.com
🌐 stackoverflow.com
Trying to get this while loop in python to do stuff.

posting wouldn't let me tab lol

More on reddit.com
🌐 r/Maya
3
1
February 12, 2020
🌐
Python
wiki.python.org › moin › WhileLoop
While loops - Python Wiki
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list. ... While loops, like the ForLoop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no ...
🌐
W3Schools
w3schools.com › python › python_while_loops.asp
Python While Loops
Python Examples Python Compiler ... Certificate Python Training ... With the while loop we can execute a set of statements as long as a condition is true....
🌐
Programiz
programiz.com › python-programming › while-loop
Python while Loop (With Examples)
In Python, we use a while loop to repeat a block of code until a certain condition is met.
🌐
Real Python
realpython.com › python-while-loop
Python while Loops: Repeating Tasks Conditionally – Real Python
March 3, 2025 - In this tutorial, you'll learn about indefinite iteration using the Python while loop. You'll be able to construct basic and complex while loops, interrupt loop execution with break and continue, use the else clause with a while loop, and deal with infinite loops.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-do-while
Python Do While Loops - GeeksforGeeks
July 23, 2025 - In Python, we can simulate the behavior of a do-while loop using a while loop with a condition that is initially True and then break out of the loop when the desired condition is met.
🌐
Python documentation
docs.python.org › 3 › tutorial › controlflow.html
4. More Control Flow Tools — Python 3.14.3 documentation
In a for loop, the else clause is executed after the loop finishes its final iteration, that is, if no break occurred. In a while loop, it’s executed after the loop’s condition becomes false.
🌐
freeCodeCamp
freecodecamp.org › news › python-do-while-loop-example
Python Do While – Loop Example
August 31, 2021 - The while loop, on the other hand, doesn't run at least once and may in fact never run. It runs when and only when the condition is met. So, let's say we have an example where we want a line of code to run at least once. secret_word = "python" counter = 0 while True: word = input("Enter the secret word: ").lower() counter = counter + 1 if word == secret_word: break if word != secret_word and counter > 7: break
🌐
Server Academy
serveracademy.com › blog › python-while-loop-tutorial
Python While Loop Tutorial - Server Academy
November 12, 2024 - A while loop in Python repeatedly executes a block of code as long as a specified condition remains true.
🌐
Stanford CS
cs.stanford.edu › people › nick › py › python-while.html
While Loop
Here's an infinite loop example caused by a typical looking bug — the variable i accidentally stays at the value 1 and the loop just goes forever. i = 0 while i < 10: # BUG infinite loop print(i) i = i * 1 print('All done')
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-while-loop
Python While Loop - GeeksforGeeks
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied.
Published   December 23, 2025
🌐
W3Schools
w3schools.com › python › python_lists_loop.asp
Python - Loop Lists
Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration. Print all items, using a while loop to go through all the index numbers
🌐
Python Morsels
pythonmorsels.com › while-loops
Python's "while" loop - Python Morsels
June 20, 2025 - Python's for loops are for looping over iterables, but while loops are for looping based on a condition.
🌐
Reddit
reddit.com › r/learnpython › 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?
r/learnpython on Reddit: 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?
September 29, 2022 -

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.)

🌐
Python.org
discuss.python.org › python help
Help with a while loop - Python Help - Discussions on Python.org
February 5, 2024 - I need help fixing up this while loop. When I place my answer I end up with the same answer “That is not A, B, C, D or E, try again:” print("1. What is the smallest unit in life? -'2points'-") print("A: organs") print("B: cells") print("C: organism") print("D: tissues") print("E: organ system") print("---------------") organs = ("A") cells = ("B") organisms = ("C") tissues = ("D") organ_system = ("E") answers = (organs, cells, organisms, tissues, organ_system) quest1s = input("?: ") while quest...
🌐
CodeWithHarry
codewithharry.com › blogpost › python-cheatsheet
Python CheatSheet | Blog | CodeWithHarry
Python uses indentation (usually 4 spaces) to define blocks. if x > 0: print("Positive") elif x < 0: print("Negative") else: print("Zero") for i in range(5): print(i) i = 0 while i < 5: print(i) i += 1 · break → exits loop · continue → skips iteration ·
🌐
Analytics Vidhya
analyticsvidhya.com › home › all about python while loop with examples
Python While Loop with Examples and Use Cases
January 31, 2024 - In this example, we initialize the variable `num` to 1. The while loop continues if `num` is less than or equal to 5. Inside the loop, we print the value of `num` and then increment it by 1 using the `+=` operator. This process repeats until `num` becomes 6, when the condition becomes False, and the loop terminates. Python provides three loop control statements, ‘ break’, ‘ continue’, and’ pass, ‘ to allow you to control the flow of a while loop.
Top answer
1 of 11
93

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.

2 of 11
24

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()
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter05.02-While-Loops.html
While Loops — Python Numerical Methods
The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon! ... A while loop or indefinite loop is a set of instructions that is repeated as long as the associated logical expression is true.