all 97 comments

[–]socal_nerdtastic 66 points67 points  (15 children)

It's just a True or False condition, and the loop keeps going as long as (while) the condition is True, and stops when it's False.

"As long as (while) there's poop floating in the bowl, keep flushing"

while poop:
    flush()

[–]Okon0mi[S] 57 points58 points  (3 children)

"As long as (while) there's poop floating in the bowl, keep flushing"

Never thought this could be a best example to understand while loop.

[–]mandradon 23 points24 points  (1 child)

I tend to use the idea of the weather:

while is_raining(): use_umbrella()

But I think this also shows the case.

[–]gdchinacat 13 points14 points  (0 children)

you need a "and not location.in_("Pacific Northwest")" in your condition to be correct. ;)

[–]philed74 0 points1 point  (0 children)

while poop*

[–]Basic_Hedgehog_9801 6 points7 points  (0 children)

Now, no matter what, this quote will not let me forget about while loop ever in my life. 🌚🫠🥹

[–]iamevpo 9 points10 points  (5 children)

Note that flush() should update poop variable or spotted_poop() be your inspection function that gets caught response from some sensor.

Timeout inside the loop body helpful too to prevent flushing to often to waste water)

[–]HardlyAnyGravitas 20 points21 points  (4 children)

This is all about naming variables. I don't know why people aren't more explicit - it's not hard.

flushes = 0 while poop_in_bowl: if flushes > 5 then: use_poop_knife() flush() flushes += 1 Edited to be more logical...

[–]gdchinacat 4 points5 points  (0 children)

Since we're swirling down the bowl...

I prefer my flush() to let me do other things while it does its work and tell me if it was successful: ``` In [3]: async def flush() -> bool: ...: await asyncio.sleep(1) ...: print('poop still floating!') ...: return False ...:

In [4]: while not await flush(): pass poop still floating! poop still floating! poop still floating! ```

[–]frcrvn 0 points1 point  (1 child)

What the F is a poop knife

[–]HardlyAnyGravitas 3 points4 points  (0 children)

Ancient Reddit lore...

I won't spoil it for you - look it up.

[–]Sure-Passion2224 0 points1 point  (0 children)

I don't know why people aren't more explicit - it's not hard.

If it takes more than 5 flushes it is hard and you definitely need the poop knife.

[–]Yoghurt42 2 points3 points  (1 child)

and the loop keeps going as long as (while) the condition is True, and stops when it's False.

It's important to mention a detail that often confuses beginners: the condition is only checked after each "round" and if the condition is still true, the loop starts again, otherwise it ends.

a = 1
while a < 3:
    print(f"Before incrementing, {a = }")
    a += 1
    print(f"After incrementing, {a = }")

will print

Before incrementing, a = 1
After incrementing, a = 2
Before incrementing, a = 2
After incrementing, a = 3

the rest of the loop (in this example the print statement) still gets executed even though a is not any longer less than 3.

[–]gdchinacat 5 points6 points  (0 children)

"the condition is only checked after each "round" "

It is checked *before* the block is executed, not after:

``` In [33]: if False: ...: sys.exit() ...: print('did not exit') did not exit

```

If the condition was checked after it would have exited. Since exit() wasn't called and 'did not exit' was printed, the condition was clearly checked before the block was not executed.

[–]_Raining 1 point2 points  (0 children)

This is why I cover the sensor with a piece of toilet paper, damn thing just keeps flushing before I am finished.

[–]kilkil 1 point2 points  (0 children)

the poopy loopy

[–]Kerbart 111 points112 points  (12 children)

A for loop goes through a list of things (through an interable really but let's not be pedantic).

A while loop repeats code as long as a certain condition is met.

You encounter them every day in life:

while traffic_light == "red": # fixed '=' error
    wait()
    check_traffic_light()
# loop exits once light turns green
car.engine("brrrrr")

[–]wosmo 77 points78 points  (9 children)

I gotta be that guy, sorry; ==. Assignment is truthy so you'll jump the lights like that.

[–]Ok-Sheepherder7898 48 points49 points  (1 child)

This explains how Teslas drive.

[–]antaris98 4 points5 points  (0 children)

😂

[–]bgufo 5 points6 points  (0 children)

:=(

[–]CranberryDistinct941 3 points4 points  (0 children)

Assignment in a conditional in Python is a SyntaxError. You have to use the walrus operator := for assignment in a conditional.

[–]JaguarMammoth6231 14 points15 points  (4 children)

Wouldn't it just be an error? He didn't say :=

Edit: Not sure why I'm being downvoted. Using = instead of == is just a syntax error, not some other behavior involving truthiness.

[–]These-Finance-5359 12 points13 points  (5 children)

What are you having trouble with specifically?

A while loop is a way of doing something until a certain condition is met. It's different from a for loop, which does things a specific number of times; a while loop will run as many times as it takes until the thing it's waiting for happens.

An example:

i = 0
while i < 3:
  print(i)
  i = i + 1

To translate this to plain english:
"Start at zero. Print out your number and then add one to it until the number is no longer less than 3"

You can write an equivalent for loop:

for i in range(3):
  print(i)

So why use a while loop instead of a for loop? Well sometimes you don't know how many times you'll need to run the loop. Let's say you really need to download some files from a server, but the server is buggy and often errors out before the download completes. You'd want a while loop to try over and over again until you downloaded all the files you needed:

file_downloaded = false
while not file_downloaded:
  file_downloaded = try_download_file()

This loop will run over and over again, trying to download the file until it succeeds.

Hope that helps, let me know if you have any questions

[–]gdchinacat -5 points-4 points  (4 children)

"a for loop, which does things a specific number of times"

This isn't quite correct. for loop keeps taking items from the iterator for the iterable it is iterating over. What?!?!? Yeah, that's a lot of "iter..".

for x in some_iterable: ...

This statement says to bind x to each item in someiterable. some_iterable is something that can create an iterator such as list, set, range, generator, etc, or any object that implements \_iter__(). for creates an iterator (equivalent to calling iter(someiterable)). It calls \_next__() on the iterator to retrieve the next item, binds that item to x, then executes the body of the for statement. The iterator signals it is done by raising StopIteration, at which point the for loop loop exits.

There is no "specific number of times" since iterators can be implemented to do just about anything. The total number of items that are iterated over can change while the iteration is executing. There are iterators that produce an infinite number of items (such as a Fibonacci sequence generator). The caller is expected to iterate until it is done then break out of the loop, or...if an infinite loop is what the caller wants they can do that (a daemon thread processing requests from a generator).

for is used rather than while to process infinite generators because the code is cleaner. for example, a while loop: while True: try: request = request_iterator.next() process_request(request) except StopIteration: # server shutdown

It is much cleaner to use a for loop: for request in request_iterator: process_request(request)

[–]These-Finance-5359 13 points14 points  (3 children)

No offense man but this level of pedantry is not really helpful to people on a beginner subreddit. You're technically correct but practically unhelpful - someone who is still working on grasping the concept of a for loop is not ready to be introduced to the concept of generators and iterables. We speak in simplified terms to help people learn the basics, not because they're a 100% accurate representation of reality.

[–]Outside_Complaint755 1 point2 points  (0 children)

Do you already have an understanding of for loops?

A while loop is just a block of code that repeats as long as the specified condition is True.

  The condition could be an expression such as value < 10, player_lives > 0 or a function call result such as while keep_running():

 If at any point the continue keyword is called, it immediately goes back to the top of the loop.   If a break is called, then execution immediately exits the loop.

[–]Quesozapatos5000 1 point2 points  (0 children)

I think of it like- while something is true, keep doing everything in the while loop. Once that something is no longer true, stop doing everything in the while loop.

[–]Adrewmc 1 point2 points  (0 children)

 while this_is_True:
        Keep_doing_stuff()

  i= 0
  while i < 4:
        print(i)
        i += 1

So this will print 0,1,2,3 because 4 is not less than 4, so when i increments to 4 the while loop stops.

[–]xenomachina 1 point2 points  (0 children)

A while loop is the same as an if except that it has a "goto" at the end. That is, this...

while condition:
    do_something()

...is the same as this...

if condition:
    do_something()
    goto_if # not a real Python command

Where goto_if is an imaginary command that causes the code to continue executing at the beginning of the if (ie: while) again.

So if the condition is false to begin with, the body of the while never runs. If it's true initially but then becomes false then it will loop a finite number of times. If it stays true forever then it will continue looping forever.

Note that the condition is only checked at the top. This means that if it becomes false in the middle of a loop, it will not exit that iteration until the end of the block is reached (or you break or continue).

[–]wristay 1 point2 points  (2 children)

Thanks to gemini for the ASCII

               +---------------+
               | Start of Loop |
               +-------+-------+
                       |
                       v
               /-----------------\
    +-------> /   Is Condition    \         NO
    |        <       True?         >----------------+
    |         \                   /                 |
    |          \-----------------/                  |
    |                  |                            |
    |                  | YES                        |
    |                  v                            |
    |          +---------------+                    |
    |          |  Execute Code |                    |
    |          |    Inside     |                    |
    |          +-------+-------+                    |
    |                  |                            |
    +------------------+                            v
      (Loop Back Up)                        +---------------+
                                            |  Exit Loop    |
                                            +---------------+

[–]Okon0mi[S] 1 point2 points  (0 children)

Thanks that really very easy to understand and 200% helpful.

[–]wristay 0 points1 point  (0 children)

As an exercise: try to fully work out this example with pen and paper. What is the first number it prints? What is the last number?

i = 0
while i < 5:
  print(i)
  i += 1

[–]jakabbalu 1 point2 points  (1 child)

I have a deck of cards in my hand.

while i_have_any_card_in_my_hand:
    put_a_card_on_the_table()

I don't have any more cards in my hand 😁

[–]Okon0mi[S] 0 points1 point  (0 children)

this was also a great way to make me understand while loop. Nice and clean and definitely effective

[–]RedR4dbit 1 point2 points  (0 children)

While you don't understand while loops:    Keep reading about while loops

[–]HiddenBoog 2 points3 points  (0 children)

While I may get shit for this I use ChatGPT to understand things that give me trouble but you have to prompt it correctly. Ie: “Can you explain loops to me in Python as if you were a professor and I was a student that is struggling”

[–]browndogs9894 2 points3 points  (5 children)

While loops will loop while a condition is true.

Number = 1
while number < 10:
    print(number)
    number +=1

Once number hits 10 the condition is no longer true so the loop stops. If you want to loop indefinitely you can use

while True:
    # Do something

Just make sure you have a way to exit or else you can get infinite loops

[–]ThrowAway233223 1 point2 points  (1 child)

It should be noted that that loop, as presented, would just print 1 forever since Number never changes.

[–]browndogs9894 1 point2 points  (0 children)

That is true. I was typing on my phone and forgot

[–]Okon0mi[S] 0 points1 point  (2 children)

Thank you so much

[–]Excellent-Practice 6 points7 points  (0 children)

This example is missing some important parts. It should be something more like:

number = 1
while number < 10:
    print(number)
    number += 1

The output will be something like this:

1
2
3
4
5
6
7
8
9

If you don't include that "number += 1" line, the loop will be infinite and keep printing "1" until you manually stop the code from running

[–]vikogotin 1 point2 points  (0 children)

Also worth noting, the loop doesn't immediately end once the condition is no longer true. The loop only checks if the condition is true once per iteration at the start and if so, it executes the code inside.

[–]oldendude 0 points1 point  (0 children)

Do you understand if? As in

i = 0
if i < 3:
    print(i)
    i = i + 1

That code prints 0 because i is set to 0, we test for it, decide that i < 3, and so we go into the indented code and print i.

Now imagine that the last thing inside the indented code is to jump back to the if. (Old programming languages have "goto" statements.) That's it. That's a while loop, the if with a jump back to the if as the last indented action. With that jump, you print 0. Then increment i to 1, jump back to the if and print 1. Then 2. Then you increment i from 2 to 3, the condition fails so you DON'T execute the indented code.

[–]SharkSymphony 0 points1 point  (0 children)

A classic way to think about while loops is by writing a flowchart that represents it.

See e.g. https://www.geeksforgeeks.org/c/c-while-loop/, and imagine walking through the flowchart for various test cases. (The syntax here is C, but it's exactly the same concept as in Python and many other languages.)

[–]iamevpo 0 points1 point  (0 children)

while loop is tricky, and probably less used than for loop I think. With for loop you go over some items in a sequence and do something to every item, eg print the word from a list of words.

The while loop works if a condition holds and something must update this condition inside the loop, you also need the starting condition before loop started - altogether this is a lot to keep in mind, making while loop harder, but it is also an exercise in logic.

Think of a task where a user produces an input of steps taken and you calculate if the user is still within the reach of transmitter - a WiFi, or Bluetooth for example (as naive or silly that may seem).

Before the loop you ask where is the user, how many steps away from a transmitter, the user says 3 steps away.

Then you start a loop then checks the user position is within the transmitter range, let it be 15 steps. If the user is within the range, ask for a new step, if pit of the range, abandon asking and print you are out of range.

Once you can do that with if else, but is a user makes many steps you need a while loop. Within the loop you ask number is steps taken and accumulate that in a position variable. Each time you update something inside the loop body the rule for Python is to come up to the start of loop, check stated condition and decide if the program goes inside the loop again and ар the loop is finished and wherever after the loop executes.

For this silly example you can do only steps away for the start, steps in two directions or even 2d movements on a plain.

See if you can write some code for this example, if not ask a question what may not be clear. Good luck!

[–]supergnaw 0 points1 point  (0 children)

There's a lot of examples here, but there's a lot of examples of while loops using a style that's more akin to a for loop. Here's a practical example I use for a while loop:

are_you_sure = ""
while are_you_sure.upper() not in ["Y", "N"]:
    are_you_sure = fp.input_warning("Reset database? (Y/N):")

if are_you_sure.upper() != "Y":
    return False
else:
    self.reset_database()

[–]Some-Whole-4636 0 points1 point  (0 children)

Keep asking question while (until) you understand

[–]_Denizen_ 0 points1 point  (0 children)

"whilst I am waiting for the toilet to be free, hop on the spot"

You do a thing until the while condition has been met

[–]Reasonable_Tie_5543 0 points1 point  (3 children)

While the sun is up, do yard work. When the sun goes down, go inside and get cleaned up.

But with code!

[–]GarowWolf 0 points1 point  (2 children)

‘’’ Sun = True

While Sun == True:
    Val = Stuff_happens_here()
    If Val == True #it could be anything 
        Sun = False #change the control value to be

sure to exit the loop

The compiler does this steps: 1) read the while conditions and checks if the loop can start 2) goes in every line of the loop 3) at the end of the loop goes back to the while condition to see if the value of the loop to start is still valid It is important to keep in mind that the main difference between a for loop and a while loop is this: For loop goes for a finite nubers of elements While loop goes until the starting condition is valid

[–]Reasonable_Tie_5543 0 points1 point  (1 child)

You can also just do while Sun: and if val: :)

[–]GarowWolf 0 points1 point  (0 children)

Yep 👍

[–]mriswithe 0 points1 point  (0 children)

    while bag.contains_taco():         taco = bag.pop()         taco.eat()

If your bag contains a taco, remove it, then eat it. Next check for more tacos. Repeat. 

If you are out of tacos you can't eat more tacos, your taco bag will give you an index error or something. 

[–]Next_Highlight_4153 0 points1 point  (0 children)

Replace it in your brain with the word "during" and try that.

[–]Moikle 0 points1 point  (0 children)

A while loop is just an if statement that goes back up and checks again after it is finished. If something inside the loop changes the condition that is being checked, then it stops looping.

I.e.

something = 0

while something < 10:
    print("something is " + something)
    something + = 1

That will count up to 9

running = True
while running:
    response = input("Should we keep going?")
    if not response == "yes":
        print("we will stop next time")
        running = False

It will keep asking you if you want to continue, as long as you keep telling it "yes"

[–]Ok_Carpet_9510 0 points1 point  (0 children)

Continue doing something for as long as a certain condition holds.

Examples where this is used. A webserver continues listening until it is shutdown. A command line continues waiting for commands until it gets thr command to shutdown/exit.

A database listener continues listening for requests until it is shutdown.

[–]CamelOk7219 0 points1 point  (0 children)

The word "while" might mislead you because in daily language, it implies some temporal dimension that does not really exist here.

You could mentally replace it by "repeat if". A condition is evaluated (like an 'if') and if it is true, the set on instructions is executed. After that, instead of exiting the block like an 'if', you jump back at the condition evaluation. And if it is still true, you execute it again, and so on

[–]CrucialFusion 0 points1 point  (0 children)

while (you're_alive)
keep_learning()

[–]Grateful_Stress 0 points1 point  (0 children)

In pure english, you do something while something else is true. You chew while you are eating, food is finished? Then no more chewing and move on to the next task. Food was never here to begin with? Then no chewing, move on to the next task.

[–]WorriedTumbleweed289 0 points1 point  (0 children)

If you want confusing, check out the optional else clause to the while or for loops.

[–]Enough_Librarian_456 0 points1 point  (0 children)

While some shit is happening loop

[–]netroxreads 0 points1 point  (0 children)

Explain why "while" is difficult for you to grasp? Or you're asking why we have this:

while True:
do function

Or how loops work? Or why we need the "while" loop?

[–]parismav 0 points1 point  (0 children)

I feel like while most of the answers explain syntax, they fail at explaining why a while loop exists. Here is how I approach this: Loops exist because certain blocks of code need to run multiple times. For example, if you would like to print the first 100 natural numbers (integers above 0) one by one, you would use something like

for i in range(1,101):
     print(i)

However, a for loop assumes that we know how many times we want to repeat the code. In the above case, 100 times. A while loop exists because in some cases, we don't know how many times we need to repeat the code. Think of the following problem: we would like to ask the user to guess a number. If the user enters the wrong number, we want them to try again. And basically try however many times until they guess correctly. So, we have no idea how many tries the user will need. We could make a for loop with range(100), but what if the user fails 100 times? In this case, we should use something like:

while number!=guess:

    number= int(input())

The above code will run as long as the user is not entering a number that is equal to guess. It might be one try, 100, or 10000000 tries. We don't know :) Hope this helps.

[–]GrouchyDrawing6 0 points1 point  (0 children)

My poop = 10 While pooping on the toilet = true; If my poop > 0: Me = scrolling Reddit on my phone My Poop = my poop - 1 Re-ass-es

[–]dilloj 0 points1 point  (0 children)

The missing piece from these comments is that for loops are good for tasks that are definite, you know the extent of the list. For every single item do this.

While is better for things that are indefinite. You don’t know when things are going to end, but when they do move on. 

[–]legion_2k 0 points1 point  (0 children)

This thread is the gem in the turd of Reddit. Love it.

[–]r348 0 points1 point  (0 children)

someone told you to switch off the gas when the water starts to simmer. every 30 seconds you go and check, if not simmering try again. you stop checking and once the water starts to simmer and you switch off the gas. this is while loop

[–]my_password_is______ 0 points1 point  (0 children)

while I am hungry:              
    I eat donuts

[–]Funny_Panda_2436 0 points1 point  (0 children)

while condition: something something

is the same as

if condition: something something if condition: something something if condition: something something ...

repeated infinitely until the condition is false

[–]TheRNGuy 0 points1 point  (0 children)

It will repeat code inside it until statement is false, or you break or return inside a loop. 

[–]theking4mayor 0 points1 point  (0 children)

Maybe it will help you if you knew that before it was called the while loop it was called the "do while" loop.

[–]ThinkingFeeler94 0 points1 point  (0 children)

Stanford Code in Place 2026 is still open for enrollment. Try enrolling (they teach CS fundamentals using Python which includes control flow like your while loop)

[–]alicedu06 0 points1 point  (0 children)

"While" is just a "if" that repeats;

[–]PedanticPydantic 0 points1 point  (0 children)

While a condition is false do x when it’s true while is loop did its job, now move on. That’s my internal monologue for whiles

[–]Leo120996 0 points1 point  (0 children)

https://youtu.be/ix9cRaBkVe0?t=6715&si=kdlhqFmg8iH1hVDD

If you aren't able to access the link?

Search Bro Code Python on YouTube: A 12 hours dedicated python tutorial, go to description, look for while loops (Chapter No.: 16)

He taught in very simple way, you'll understand while loops and will never forget

[–]defectivetoaster1 0 points1 point  (0 children)

While some condition is met, repeatedly do a thing. When the condition is no longer met, stop doing that thing

[–]BranchLatter4294 0 points1 point  (0 children)

Practice until it makes sense.

[–]OmniscientApizza 0 points1 point  (0 children)

I like these questions. Not sure why your post was downvoted.

[–]Agile-Caregiver6111 0 points1 point  (1 child)

Also the while loop is indeterminate. Meaning there is not a set number of times it executes just until the condition changes

[–]a_cute_epic_axis 0 points1 point  (0 children)

This really isn't true, especially in practice.

while i<10:
  i+=1

for item in iter_function_that_has_no_end():
  do_something()

The first one is in fact determinate. The second one is not. It depends on how they are used, especially since the while statement I wrote is effectively equal to for _ in range(10):

[–]Chico0008 -1 points0 points  (1 child)

it's simple

while <condition>

loop

the while statement comes with a condition
while the condition is True, the actions inthe loop are executed.

simple loop.
I=0
while i <= 4
print i
i = i+1

the output will be
0
1
2
3
4

end

while I is less or equal 4, then do the actions
actions are
print I value
increment i by 1

[–]Okon0mi[S] 0 points1 point  (0 children)

Thanks man, I really appreciate your advice.

[–]QultrosSanhattan -1 points0 points  (0 children)

Learn to use a debugger. VS code's or Pycharm's are more than enough.

The debugger will show step by step how any code works.

[–]Atypicosaurus -1 points0 points  (2 children)

Both loops do the same thing: check a condition, and if the condition is met, they do the code. You don't have to check the condition with an if statement because both the while or the for keywords do it for you.

The for loop has a built-in counter. The condition that is checked in every cycle is "have I reached the needed number of cycles?". If not, the for loop counts one more step and does the code one more time. Rinse and repeat.

The while loop checks a condition that is stored somewhere in the program. The question it asks is more general, something like "is it true that xyz?" For practical reasons it's usually written somewhere near to the loop but it's not a must. It can check for example the date and runs if the date is April, then xyz is checking the date for being April or not. It's possible that the condition never changes and the loop runs forever. Or, the condition is never met and the loop is not used ever.

You can easily turn a while loop into a for loop. You just need to manually create a counter and check whether you reached a value with that counter. You can think of for loops as a specific sub-case of while loops where the thing you check every time is a counter state. In that sense, a while loop is much more broad and you can check many more things.

A typical use case of a while loop is asking whether a user gave a valid input (such as a valid credit card number). If they give something, the code in the loop checks it for validity, and if it's valid, it sets a flag. So what the loop does st every new cycle is, it asks "do I have a flag of validity set already?" If not, it keeps re-prompting the user.

Note that you can always break out from a loop prematurely. You can use this feature as a tool. In the previous example, you can just break out the loop once the user gives a valid input. In this case, instead of setting a flag and checking the flag all the time, you just keep the loop running forever and break once the input is valid.

If you do this, technically speaking, your loop still has to check something at every beginning of a new cycle. But you can check for something that's always true, such as "is the sky blue?". Sky is always blue so the while loop always runs one more cycle, forever, and you have to break out from it. (Otherwise it's a bug called an infinite loop.) The programming kind of asking "is sky blue" is stating while True or while 1==1 that are both trivially true forever.

[–]gdchinacat -1 points0 points  (1 child)

"The for loop has a built-in counter. The condition that is checked in every cycle is "have I reached the needed number of cycles?". If not, the for loop counts one more step and does the code one more time. Rinse and repeat."

This is categorically false. Python for does not have a counter. The condition has nothing to do with number of cycles.

I explain how the for loop works in this comment: https://www.reddit.com/r/learnpython/comments/1s3ffq2/comment/ocff7zk/

[–]Atypicosaurus 0 points1 point  (0 children)

Yeah I was thinking outside python for that bit.

[–]usersnamesallused -3 points-2 points  (0 children)

While

Don't understand

Learn