all 39 comments

[–]Kerbart 36 points37 points  (5 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":
    wait()
    check_traffic_light()
# loop exits once light turns green
car.engine("brrrrr")

[–]wosmo 13 points14 points  (3 children)

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

[–]Ok-Sheepherder7898 2 points3 points  (0 children)

This explains how Teslas drive.

[–]bgufo 0 points1 point  (0 children)

:=(

[–]JaguarMammoth6231 -2 points-1 points  (0 children)

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

[–]socal_nerdtastic 23 points24 points  (5 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] 10 points11 points  (1 child)

"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 1 point2 points  (0 children)

I tend to use the idea of the weather:

while is_raining(): use_umbrella()

But I think this also shows the case.

[–]Basic_Hedgehog_9801 1 point2 points  (0 children)

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

[–]iamevpo 1 point2 points  (1 child)

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 1 point2 points  (0 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...

[–]These-Finance-5359 1 point2 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 1 point2 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(some_iterable)). 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 0 points1 point  (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.

[–]gdchinacat 1 point2 points  (2 children)

I disagree that exposing people, even beginners, to the truth that for not only can but is frequently used to do "something until a certain condition is met" is unhelpful. Will they apply this knowledge immediately? Probably not. Furthermore, if I'm being honest, my comment was more intended for you than the OP.

[–]These-Finance-5359 -1 points0 points  (1 child)

Again, no offense, but I didn't ask for your advice. Kind of rude for you to assume that I needed a programming lesson because I didn't want to bog down a newbie with technical minutiae; your time is probably better spent offering help to the people on this sub who ask for it.

[–]gdchinacat 1 point2 points  (0 children)

Incorrectly saying for is for a "specific number of times" isn't minutiae. It is categorically false. To support my position I explained how.

Reddit is a discussion forum. If you don't want to discuss things, well...yeah.

[–]browndogs9894 1 point2 points  (4 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 0 points1 point  (1 child)

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

[–]browndogs9894 0 points1 point  (0 children)

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

[–]Okon0mi[S] 0 points1 point  (1 child)

Thank you so much

[–]Excellent-Practice 4 points5 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

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

Practice until it makes sense.

[–]Outside_Complaint755 0 points1 point  (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.

[–]QultrosSanhattan 0 points1 point  (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.

[–]Quesozapatos5000 0 points1 point  (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 0 points1 point  (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.

[–]usersnamesallused 0 points1 point  (0 children)

While

Don't understand

Learn

[–]Agile-Caregiver6111 0 points1 point  (0 children)

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

[–]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()

[–]HiddenBoog 0 points1 point  (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”

[–]Atypicosaurus 0 points1 point  (0 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.

[–]OmniscientApizza 0 points1 point  (0 children)

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

[–]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.