What is the actual difference between a for loop and a while loop?
Posted by Sofiatheneophyte@reddit | learnprogramming | View on Reddit | 41 comments
please don't judge me, I'm a complete beginner. I've been googling this for a while and I think I kind of get it but I'm not sure.
from what I understand a for loop is when you already know how many times you want to repeat something, and a while loop is when you keep going until a condition is false. But then I tried writing both and got the same result which confused me a lot:
```python
for i in range(5):
print(i)
i = 0
while i < 5:
print(i)
i += 1
```
BagParticular9982@reddit
Think of it like this example involving counting, by starting from 0 and counting up:
For loop - counts up to a specific number you want it to, where it then ends the loop once you reach that specific number you want it to
While loop - counts infinitely UNLESS you set a condition in the loop for it to stop at a certain number.
For loops are best used when you know how far up you'd like to count, whereas a While loop will just keep counting with no stop time by default.
Tldr; For loop is like a Timer while a While loop is like a Stopwatch
mredding@reddit
At a high level - regarding language and expressiveness and NOT Python specific, the point of having different, equivalent constructs, such as different ways of looping, is for what I've already said: expressiveness. What becomes the most natural language to express what you're doing? Often when iterating a range,
foris more natural - "for each bullet", whereas awhileis relative to a predicate - "while the bear is distracted".Do try to be as expressive as possible. Interact with a range at a high level, iterate the elements. Don't treat it as a lower level object that needs to be indexed. If you NEED the index, you can always
for i, element in enumerate(range):. If you have some skip-indexing, you can filter. Whatever you're trying to do, it's worth Googling for a minute to find a crisp way to do it. Source code is meant to be read, and it's meant to be expressive.Now back to Python proper - there are differences between
forandwhile. Theforloop is a simpler construct that allows for more aggressive optimization within the interpreter, so they tend to run faster than awhileloop. This is yet another reason to be expressive about your code, and not treat it all as dumb primitives. Since awhileloop is dependent upon evaluating a predicate of some arbitrary complexity, and other considerations, the cost of awhileloop shouldn't be considered significant for it's expressive use cases.If you can use a
forover a range - always do it.In other languages - like C, the different loop constructs are all directly equivalent, and all reduce to
gotounder the hood. In languages that support Tail Call Optimization, all loops tend to reduce to a function call that resets the instruction pointer.So be expressive first, and consider your language second.
Dependent-Aide-388@reddit
Iterating over things --> for loop
Waiting for a single condition to change --> while loop
These are rules of thumb, break them as often as you care to.
YakubReddit@reddit
whileloop:for loop:
Compiler:
x86-64 gcc 13.2Flags:
-O0So yeah, as you can see there's little to no difference. For-loops are more comfortable to use in some scenarios, but other than that they're completely the same for the compiler.
desrtfx@reddit
Yes, as has already been said this is true for c-based languages.
OP is talking about Python, which doesn't know the concept of a C-style for loop.
Python only knows C#, Java, JavaScript style for-each loops.
And because of that these loops are never equivalent in Python.
Drumroll-PH@reddit
You understood it correctly, and your examples produce the same result because both loops are counting from 0 to 4. A for loop usually handles the counting automatically when you already know the range or sequence, while a while loop gives you more control because you manually manage the condition and incrementing. While loops are more useful for situations where you do not know beforehand how many times the loop should run.
CreativeGPX@reddit
You can always use either.
For loops are a shorthand for some common extra code you'd have to add to a while loop to make it go through a sequence/set: assigning a variable for the current item or index, incrementing or interacting with an iterator, grabbing associated keys, etc.
Using shorthand can save your time, but perhaps more importantly using a common structure makes it easy for other programmers or future you to see at a glance what is happening.
throwaway6560192@reddit
Why? There's always more than one way to achieve any given result
WardosBox@reddit
Use a for loop when you are looking at a specific collection of items, a list, or a set number of rounds
Use a while loop when you are waiting for something specific to change or happen, and you have no clue how many cycles it will take to get there.
If you have to read 20 pages, you know exactly you have to read 20 pages (for)
And if you play a video game. How long? Well, you dont know. Like while game_is_running: print("is playing the game") (while)
Monster-Frisbee@reddit
To extend your reading analogy, a while loop is like reading until you find a quote you were looking for.
crashomon@reddit
Great analogy
WardosBox@reddit
I head back to class and tell my old teacher :P
It's exactly how he explained it to me way back and it clicked immediately
zeekar@reddit
These constructs all exist to enhance program readability. You can always get the same result in multiple ways.
In the old days you would use GOTO, something like this (not that Python has GOTO):
The problem with such code is that it's easy to lose sight of the loop increment and condition when they're at the bottom of what might be a long loop body, which might also have a lot of other
ifs besides the one that loops back to the beginning. Awhileloop lets you move the condition up top so you can easily see how long it will loop for:But the increment step is still hidden at the bottom of the loop body. A
forloop raises that up to the top as well. The C language's version is very general and uses the same instructions as awhile, just moved into a special header at the top of the loop:The Python version is instead what many languages call
foreachbecause it iterates through a list of items and does something for each of them. You often want to count, which is the same as looping through a list of numbers, which you can construct usingrange():That's much clearer - you only need one line to tell you that it's going to loop five times with
itaking on the values 0, 1, 2, 3, and 4. And that line is right at the top of the loop code.You could also use an explicit list:
but the nice thing about
range()is that it's lazy - it doesn't actually construct a list unless invoked in a context that needs one, whichfordoesn't. It just produces the next number every time theforcode asks for one, until there aren't any more. So even if you're counting up to a very large number, Python doesn't have to first create a ginormous list of every integer from 0 up to that number before starting the loop.fixermark@reddit
A for loop is a much more convenient short-hand for a while loop.
For loops are, in Python, iterating loops (as opposed to the older style counter-loops in other languages, which give you more control but carry the risk of botching the math and creating something other than you intended). They give you the nice advantage that you can expect to see every element in the collection, exactly once. Under the hood, they're three things:
You can write any for loop as a while loop by doing those three things around your while loop, but it means you could forget to do one (or do it wrong), so the for loop gives you some convenience guarantees.
high_throughput@reddit
Note that syntax is
for vars.. in Xfor some sequence X.range(N)happens to be a collection of numbers from 0 to N, and therefore a common pattern to iterate over numbers.You can also do
capitals={ "Spain": "Madrid", "Italy": "Rome" } for country, capital in capitals.items(): print("The capital of " + country + " is " + capital)
so don't get too hung up on the "number of times" aspect
carcigenicate@reddit
If just like to point out that while the general advice of "use a for loop when you know how many times you want to loop" isn't awful as starter advice, it's not very accurate.
forloops can be used to iterate infinitely.The purpose of a
forloop is to do something for every element in an iterable. Typical iterables that you're used to are lists, tuples, and dictionaries. They're anything that can produce an iterator that can be iterated. So, you use aforloop when you have an object that you want to iterate over.The main mental hurdle I think is when you're iterating over a
range.ranges are iterables, like lists, that can be iterated over. The main difference is, ranges "contain" a series of numbers, instead of arbitrary objects (in reality, though, they don't contain much. They actually just compute each element on the fly as they're requested).zoddrick@reddit
for loops => when you need to perform something a specific number of times
for every card in this deck
for every row in this database
for every person in the country
while loops => when you need to do something while a condition is being met
while it is raining outside, keep windows up
while its sunny outside, keep windows down
while card == spade or diamond draw another card
Now there are a lot of languages that write each of these differently and they can provide some subtle bugs if you arent used to it but in the end they are still loops that are performing a task for a given condition.
eruciform@reddit
They're interchangeable
But some things are easier to phrase properly in one or the other
Pick whichever is easier for your particular use case
WystanH@reddit
In other languages, a
forloop and awhilecan be directly compared for functionally. However, python doesn't technically have aforloop but rather aforeachloop.Consider some loops in javascript.
See that second option? Python just doesn't have it.
So the above in python is only the two available loops:
Keeping in mind here that
rangeconstructs an iterable object.Sometimes that iterable object would also be nice with an index counter, that you would normally get from a basic
forloop. The python solution is to add a counter to the iterated result with enumerate.InsanityOnAMachine@reddit
For loops run on an iterator, which is a semi-advanced programming topic, and While loops run on a condition.
Basically, range(), which beginners are just taught to use to iterate a fixed number of times, is actually a function that returns an object! Try writing
print(range(5))
to see what it returns. For loops can only run on this sort of object, and range() is just one of many functions that return an Iterator object. Try going
for element in ["a", "b", "c"]:
print(element)
and see what happens; the list in this case turns itself into an Iterator for your convenience.
While loops run until a condition resolves to false; so
while i < 5:
i += 1
print(i)
will check every loop if i is less than 5, and if so, keep running. You can also have more advanced conditions, like maybe for example you have a function that returns true as long as it's the weekend;
while isWeekend():
print("Still the weekend!")
Hope this clears things up!
ExcitingSympathy3087@reddit
For Loop has start stop and step in code. Example: for(int i = 4; i < 10; i +=3) {}
while loops need a termination condotion when you want to stop the loop.
but its possible to code all for loops as while loop.
While loops are always better if you wait for something. Boolean true….. terminal menus etc.
desrtfx@reddit
That's for C-based languages.
OP is talking about Python where
forloops are more like for each loops in e.g. C# or JavaExcitingSympathy3087@reddit
This makes in programming basics no difference but i know what you mean. I agree syntactically For python the same code: for i in range(0, 10, 2): print(i)
Always in every language basically exist only loops, conditions, variables, and functions(methods). There exist only different syntaxes in c , java, python….
desrtfx@reddit
I have to nitpick a bit here as Python is different.
Yes, on a surface level
for i in range(4, 10, 3):in Python is the same asfor(int i = 4; i < 10; i +=3), but in reality it is fundamentally different.The
rangefunction generates an iterable, think of it like a list with the values of the range, e.g. [4, 7] in that case andforiterates over these elements, not directly over the numbers.A
forloop in Python is a for-each loop in other languages. There is no C-like for in Python, even though it might look like that.randumtacoz@reddit
You're having both loops do the same thing essentially. In the For loop, you're having it iterate (count for simpler terms) through a range up to 5 numbers, and in the While loop, you're adding to a variable while it's less than five. They seem similar in this situation and they are similar, but they have slightly different use cases.
A while loop will generally be used when you explicitly need something to stop at a certain point, but you don't know when that point will be, like you need a user to type yes or no but you need the prompt to stay up until they type yes or no. You use a while loop to say "keep repeating this until the user has input yes, or no, otherwise continue.
while input != yes || input != no: continue
A for loop is more for when you know that you needed to end at some point, like iterating, or looking through say a list, or array, that could be changing sizes (like a list of numbers that grows but you need to perform math on all of those numbers) but you need to be able to read the whole list of data for something every time no matter how big the list is or how small the list is.
for number in list of numbers -1 each number print that new number from list
Emptyell@reddit
They can produce identical results as you have demonstrated.
The key difference is that the for loop will always terminate once it’s reached the limit value.
The while loop will run until the termination condition is met. For example if replace your while condition with variables such as “while x < y:” it will continue until x >= y which may or may not occur depending on what happens in the loop.
So while loops are handy when you don’t know how many iterations it will require (constant or variable) but it does run the risk of running forever if the terminate condition is never met.
Valuable-Ear-9543@reddit
Not a ton! Here's the main differences:
in a while loop, there is no auto-incrementation. If you want something incrementing, you've got to make sure it happens somewhere within the loop
For loops run for basically a set number of loops (unless exited early) because it's iterating through a certain range
While loops run until their condition evaluates as false. They're best for loops where you don't know how many times they may need to run.
In some languages, there are do-while loops (I don't think python has them) - for those, they run once and then it's a normal while loop where the condition is evaluated before running
eckzie@reddit
Whole loops are for when you don't know when it will stop looping and can be written so they are functionally the same as a for loop.
Let's take a simple program, it asks the user to type a message then it takes what they wrote and adds an exclamation point. If you want the user to do it again without the program closing you need to use a loop. A for loop will ask the user however many times you've indicated while writing the loop.
Instead, you could use a while loop and insert a question at the end of they'd like to do it again. When they say no you can exit the loop. This is very different functionality than what a for loop can do (I mean you can technically do this with a for loop as well but why).
This is just a simple example but there are lots of times a while loop is way better.
lurgi@reddit
Every for loop can be written as a while loop and vice versa. The choice is entirely a matter of personal preference and clarity of code.
Typically you’ll use a for loop when the problem is naturally stated in terms of “do this a certain number of times”. Typically you’ll use will use a while loop when the problem is naturally stated in terms of “do this while this condition is true”. Either one can be used, it’s a matter of style and clarity.
BeginningOne8195@reddit
You actually understood it correctly. The reason you’re confused is because both loops can produce the same result, they’re just designed for slightly different situations.
idiotiesystemique@reddit
Almost everything can be done in either, but many things are best done or clearer in a specific one. A while loop just checks if the exit condition is met. A for loop is meant for iterating over a collection or incrementing a value. So generally speaking, a simpler way to look at it is
"is my condition met?" = while
"am I done iterating over this collection?" is a for loop
BioHazardAlBatros@reddit
You already know it. Under the hood for loop is just a while loop with extra steps. The difference is in their usage: Your example is bad. Look at it another way: "The app has to work as long as the user didn't hit certain button". Can you write loop condition for such functionality using
forloop? (The answer is yes, but it will look way less readable than simplewhileloop)nicodeemus7@reddit
Used as intended, a for loop has a limit, and a while loop in infinite.
However, you can usually use the interchangeably. In essence, a for loop is a limited while loop, and a while loop is an infinite for loop.
(for i in (0, 100):) is the same as (while i < 100 and i >= 0: i += 1)
ekvivokk@reddit
It's how you use it, and readability.
Lets say you want to use pandas to create one workbook for each worksheet in an existing workbook.
You could do
but that's a rather contrivied way of doing it. It's much easier to both read and write.
While if you want to create something like a CLI to do stuff with user input, a while loop makes much more sense
Here writing it with a for loop is harder, I'm actually not sure how I would do that with a for loop.
desrtfx@reddit
In most programming languages, a
forloop is basically syntactic sugar, convenience for awhileloop with an automatic adjustment of the loop iterator.In most C based languages the following is (close to) equivalent:
and
The main difference between these two loops is the scope, the visibility of the iterator
i. In theforloop,iwill be out of scope after the loop, in thewhileloop it will stay in scope.In Python,
forloops follow a different concept. They generally iterate over an iterable - this is any form of a collection, like a list, dictionary, range, generator, etc.The
rangefunction basically (not 100% correct) creates a list of values to iterate over.So, your Python
forloop is more like:The
whileloop on the other hand is and does exactly what you describe.BranchLatter4294@reddit
You can always write any for loop as a while loop. This is expected behavior.
Philluminati@reddit
Nothing is actually different under the surface. Programming languages offer both because they speak for the developer's intentions. `For` visits every item in a sequence once. `for car in carList` is self-explanatory. while takes a boolean so `while (waitingForBackgroundJobToFinish)` is a more logical reason to use a while loop. For wouldn't fit so well here since you don't have defined bounds.
AdministrationMoney1@reddit
Functionally you can make them do the same thing, it's just convention that a for loop is used for iterations with your indexing example, a while loop more common for other other kinds of conditionals like `while not container.empty():`
Isgrimnur@reddit
In the case you've written, not much. While loops are generally used for open-ended loops, ones where you don't know when it will stop.
You wouldn't use a for loop to process an incoming file. It might be five lines, might be 15, etc. While not end-of-file is a better example.
jbiemans@reddit
I think the main difference is that the for loop will increment the counter on its own every pass, but the while loop doesn't and you have to manually change it like you did in the op.
But I don't know enough either, so I am looking forward to what others say.
ParshendiOfRhuidean@reddit
What difference in result were you expecting, and why?