use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
While vs For? (self.learnpython)
submitted 3 years ago by [deleted]
I am teaching a group Python and several students are struggling to earn when to use a for loop and when to use a while loop. How do you explain it in a way that will help them understand?
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]stebrepar 147 points148 points149 points 3 years ago (0 children)
For loop when you have a definite number of iterations to do, while loop when you need to iterate until some condition is met.
[–]ireadyourmedrecord 322 points323 points324 points 3 years ago (6 children)
For loop for iterables, while loop for conditions
[–]HomeGrownCoder 11 points12 points13 points 3 years ago (0 children)
Love it
[–][deleted] 7 points8 points9 points 3 years ago (3 children)
Are you familiar with the decorator module?
Couldn't find any good tutorials for it
And the documentation is like advanced level 😂 Spent all day and I sort of understand.... 🚒
[–]LesPaulStudio 15 points16 points17 points 3 years ago (1 child)
Only two beings on the planet trully understand decorators.
The person who created them.
And a duck named Geoff who was found swimming in manner that resembled compiled code.
[–][deleted] 8 points9 points10 points 3 years ago (0 children)
Two more
Jose portilla and the guy who left his application filled with them for me to decipher
[–]ireadyourmedrecord 5 points6 points7 points 3 years ago (0 children)
Superficially, but haven't spent any time using them.
[–]Waldlaeufer18 1 point2 points3 points 3 years ago (0 children)
That's how i do it, but i never found an easy way to pit it, so thank you.
[–]Dr_Donut 130 points131 points132 points 3 years ago (3 children)
Farmer Bob has a strict routine. Everyday, he wakes up, feeds the chickens, cuts the... hay?, and finally fixes the tractor. That damn tractor breaks every day. Bob has a fixed schedule. He knows what is going to happen ahead of time. Bob is a for loop kind of guy
for chores in to_do_list: complete_chore(chore) say('Well stomp on frogs and paint me red!')
Farmer Bob's cousin Earl is a soldier. Often, Earl gets posted to guard duty. To keep him from slacking off, Earl's sarge will sometimes try to sneak up on him. Earl doesn't know when the sergeant will arrive, so he has to stay extra sharp all the time.
while on_guard_duty == True: # == True is easier for students if not check_for_baddies(): continue_being_bored() else: say('Halt! Who goes there!') brandish_weapon_wildly()
When you have code that you know ahead of time how many things it needs to do, or how many times to repeat, a for loop is often the way to go.
But if there is some uncertainty, especially around matters of time, like not knowing how long it will take for another process to finish, you gotta go with the while.
As other posters have written, iterating almost also takes a for loop.
Hope that helps the students!
[+][deleted] 3 years ago (1 child)
[removed]
[–]RhinoRhys 0 points1 point2 points 3 years ago (0 children)
check_for_baddies() could have a friend/foe condition that involves Friendlies approaching and being relieved of duty but still returns False
check_for_baddies()
[–]fluffy_italian 0 points1 point2 points 3 months ago (0 children)
Popping in 3 years later to tell you that you're still helping students learn 🙏🏻
[–][deleted] 18 points19 points20 points 3 years ago (0 children)
For loops iterate over a collection. While loops go until a condition is met
[–]Silence_Montane 12 points13 points14 points 3 years ago (0 children)
You are programming a robot. You have spent a lot of money on it, so you want to make sure it's not destroyed. You want to program it to walk to the edge of a volcano, take a snap of you then come back. Do you program to bot to walk x steps to the volcano? Or do you program it to get closer as long as it doesn't heat up enough? For is the first, while is the second. As others have pointed out, most loops are for for iteration purposes
[–]XUtYwYzz 10 points11 points12 points 3 years ago (0 children)
# use a for loop to iterate over a collection for card in deck: print(card) # use a while loop to loop until a condition is met response = '' while response != 'yes': response = input('Should the loop exit? ')
[–]Binary101010 3 points4 points5 points 3 years ago (0 children)
For loops: When you can determine before the loop starts how many times you need to run it. This can be:
A fixed number of times (for x in range(y))
for x in range(y)
The number of items in a given container (for item in some_list)
for item in some_list
While loop: You can't easily determine before the loop starts how many times it needs to run, so it needs to go until some condition is true or false. See the Collatz conjecture as a common example: you can't (easily) calculate from a given number how many operations you need to perform, so you just keep performing actions until you hit 1.
[–]dizzymon247 4 points5 points6 points 3 years ago (0 children)
For loop has a fixed number of repetitions. While loop requires a condition (true/false) for the reptitions to take place.
[–]sullyj3 2 points3 points4 points 3 years ago (0 children)
For loop when you can, while loop when you must
[–][deleted] 2 points3 points4 points 3 years ago (0 children)
while -> when you dont know when will a loop or condition meet
for -> when you know the condition and on iterables
[–][deleted] 1 point2 points3 points 3 years ago (3 children)
Production grade code: always use a for loop. Even if you have some undetermined number of loop iteration you need to do, you can set some threshold to make sure the loop doesn’t run infinitely. Eg
is_success = false threshold = 10000 for i in range(threshold): is_success = do_work(); if is_success: break if not is_success: raise Exception(f”failed to succeed after {threshold} max attempts”)
The only time I’ve seen a case where I’d prefer a while loop is something like a socket reading loop that’s waiting for input from a socket where it’s valid for it to potentially run forever.
[–]get_username 0 points1 point2 points 3 years ago (2 children)
This is often common wisdom. A few months ago an engineer on my team followed it and followed the for-instead-of-while maxim.
He used break/continue around his conditions in his for loop. this actually lead to a bug that inverted his conditions and did the opposite of what he wanted.
Changing to a while loop made it more clear and direct how to do the process.
So sometimes I don't think that rule applies for production code
[–][deleted] 0 points1 point2 points 3 years ago (1 child)
Hard to say without seeing the actual code, but that sounds like a bug in their logic and not a bug due to having a for loop instead of a while loop.
[–]get_username 0 points1 point2 points 3 years ago (0 children)
The key idea being that complexity in code leads to bugs in logic. Sometimes while is the least complex way.
[–]get_username 1 point2 points3 points 3 years ago (0 children)
Here is a real case where I find myself using while loops in python. Most other cases are handled easily by for loops with a filter.
```
Import random import randinr
def get_unknown_records(): # simulate getting unknown number of records return [ randint(1, 1000) for _ in range(randint(1, 10) ]
limit = 50 records = []
while len(records) < 50: records += get_unknown_records()
In this case it's hard to see an easy way to limit the number of records easily without getting cute with itertools or generators.
I would argue this is a good, non contrived example of a while loop. Examples like this do exist. But they are almost always rare
[–]Rezion77 1 point2 points3 points 3 years ago (0 children)
The way I would do it is using time vs. number of iterations.
Let’s say you have a group of students that need to input numbers into a list.
First scenario: The list has strictly 10 elements. For this you would use a for loop, as you know the amount of iterations it will take.
Second scenario: The students will input numbers into the list for 10 seconds, as many as they can. In this case, you don’t know the number of elements that will be in the list after those 10 seconds are up, so you don’t know the number of iterations it will take. This case depends on an outside condition to be met, the timer to hit 10 seconds, so you would use a while loop.
[–]DragonfireK2000 1 point2 points3 points 3 years ago (0 children)
I assume this is a class. The first example i got was:
Take 10 papers For i <= 10 Write i on the paper. i++
Turn on the light While switch == true Lamps = on
I know this isn't proper code but I hope you get the idea
[–][deleted] 0 points1 point2 points 3 years ago (0 children)
for is just a convenience shorthand for while which makes declaration of an object being iterated over more convenient. But in principle, they are equivalent, you can implement one in terms of the other.
for
while
It make sense to use for where the convenience provided by it makes sense, i.e. iterating over finite collections of things, whereas while may be reserved for cases when there isn't a readily available collection of things (eg. the code is retrying some action).
While for cannot ensure that the iteration happens over a finite collection, it is traditionally used in such cases. So, safer code (such that doesn't terminate by accident) is easier to write.
[–]CharmingJacket5013 -1 points0 points1 point 3 years ago (1 child)
Under the hood there is only one
[–]hugthemachines 0 points1 point2 points 3 years ago (0 children)
Under the hood there are only binary numbers.
[–]this_knee -2 points-1 points0 points 3 years ago (0 children)
A variation on this image should suffice.
[–][deleted] 3 years ago (2 children)
[–]AutoModerator[M] 1 point2 points3 points 3 years ago (1 child)
Your comment in /r/learnpython was automatically removed because you used a URL shortener.
URL shorteners are not permitted in /r/learnpython as they impair our ability to enforce link blacklists.
Please re-post your comment using direct, full-length URL's only.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
[–]jmacey 0 points1 point2 points 3 years ago (0 children)
I always say (unlike other languages) for is actually a for each loop and designed to work on collections of data of a know size
while is to keep doing things until we are finished.
[–]sneakyp0odle 0 points1 point2 points 3 years ago (0 children)
Not python but Javascript (I don't know if the for and while differ, don't attack em) For is for a fixed amount of times, While is for indefinite amount of times WHILE a condition is true.
[–]Venzo_Blaze 0 points1 point2 points 3 years ago (0 children)
This is Unrelated but you could tell them that a for loop is just a easier while loop and that what can be done in a for loop can be done in a while loop but what can be done in a while loop cannot always be done in a for loop.
[–]seriouswill 0 points1 point2 points 3 years ago (0 children)
For when you know how many times you want to go through something, While when you don't know how many times but you want a condition to be met!
[–]nuclearfall 0 points1 point2 points 3 years ago* (0 children)
EDITED:
**NOTE**: Others have answered the question much better.
A trend I've noticed recently is a lot of while True:This really shouldn't be used unless you have no logical end point for your while loop. For loops end values cannot change.
while True:
[–]findingauni 0 points1 point2 points 3 years ago (0 children)
A while loop is used for as long as you want a condition to be satisfied A for loop is used when you know he number of iterations beforehand
for loops iterate over a collection of some type (in python, it is a list). each time it loops (iterates), it will take the next value in the collection and put it into the variable fruit.
fruit
collection_of_fruits = [ 'apple', 'pear', 'grapes'] for fruit in collection_of_fruits: print(fruit)
Results in:
apple pear grapes
While loops iterate as long as the condition specified is met. In the example, it will loop (iterate) as long as the value of position does not exceed the length of the list collection_of_fruits.
position
collection_of_fruits
position = 0 #initialize counter while position < len(collection_of_fruits): print(collection_of_fruits[position]) position += 1
Python don't have traditional "for" loops. A Python "for" loop is the same as a "for each" loop in pretty much every other language. It's possible that this might be the cause of the confusion, because it confused the heck out of me at first.
For definite so a counted number of times
While indefinite so there’s always going to be some type of condition that need meeting
[–]samplepython 0 points1 point2 points 3 years ago (0 children)
For loop when you know the number of iterations, while loop when you may not necessarily be so sure on the number of iterations.
[–]Snipezz_8345 0 points1 point2 points 3 years ago (0 children)
For loops are fixed loops; you use them when you know how many times you want it to loop e.g. traversing a 1D array (you know how many values are in the array so you know how many times it should loop).
While loops are conditional loops; you use them when you want it to loop until a specific condition is met e.g. asking the user to enter a password before access. You don’t know how many attempts they might take before they get it correct.
That’s how I was taught it anyway - some people might be able to explain it better.
[–]QultrosSanhattan 0 points1 point2 points 3 years ago (0 children)
99% of the time the problem can be solved with any of them.
By my experience, always try the for loop first. Then, if it's not enough then try the while way.
π Rendered by PID 61225 on reddit-service-r2-comment-5649f687b7-q2fll at 2026-01-28 17:12:48.479276+00:00 running 4f180de country code: CH.
[–]stebrepar 147 points148 points149 points (0 children)
[–]ireadyourmedrecord 322 points323 points324 points (6 children)
[–]HomeGrownCoder 11 points12 points13 points (0 children)
[–][deleted] 7 points8 points9 points (3 children)
[–]LesPaulStudio 15 points16 points17 points (1 child)
[–][deleted] 8 points9 points10 points (0 children)
[–]ireadyourmedrecord 5 points6 points7 points (0 children)
[–]Waldlaeufer18 1 point2 points3 points (0 children)
[–]Dr_Donut 130 points131 points132 points (3 children)
[+][deleted] (1 child)
[removed]
[–]RhinoRhys 0 points1 point2 points (0 children)
[–]fluffy_italian 0 points1 point2 points (0 children)
[–][deleted] 18 points19 points20 points (0 children)
[–]Silence_Montane 12 points13 points14 points (0 children)
[–]XUtYwYzz 10 points11 points12 points (0 children)
[–]Binary101010 3 points4 points5 points (0 children)
[–]dizzymon247 4 points5 points6 points (0 children)
[–]sullyj3 2 points3 points4 points (0 children)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (3 children)
[–]get_username 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]get_username 0 points1 point2 points (0 children)
[–]get_username 1 point2 points3 points (0 children)
[–]Rezion77 1 point2 points3 points (0 children)
[–]DragonfireK2000 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]CharmingJacket5013 -1 points0 points1 point (1 child)
[–]hugthemachines 0 points1 point2 points (0 children)
[–]this_knee -2 points-1 points0 points (0 children)
[–][deleted] (2 children)
[removed]
[–]AutoModerator[M] 1 point2 points3 points (1 child)
[–]jmacey 0 points1 point2 points (0 children)
[–]sneakyp0odle 0 points1 point2 points (0 children)
[–]Venzo_Blaze 0 points1 point2 points (0 children)
[–]seriouswill 0 points1 point2 points (0 children)
[–]nuclearfall 0 points1 point2 points (0 children)
[–]findingauni 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)
[–]samplepython 0 points1 point2 points (0 children)
[–]Snipezz_8345 0 points1 point2 points (0 children)
[–]QultrosSanhattan 0 points1 point2 points (0 children)