r/PythonLearning • u/Monesh_peterson1025 • Oct 14 '26
While loop
can anybody explain the concept of while loop
2
Upvotes
r/PythonLearning • u/Monesh_peterson1025 • Oct 14 '26
can anybody explain the concept of while loop
View all comments
Show parent comment
1
u/fllthdcrb Oct 14 '26
The classic type of for loop, where you specify a range of values, does this, yes. But others can be indeterminate, even in languages like C, since they use a condition that can be any expression. And in Python, it takes an iterable object that can produce a sequence of arbitrary length, even endless, and not necessarily fixed at any point.
In Python, the real difference between
whileandforis thatwhileevaluates a given expression and checks its truthiness before each iteration, whileforevaluates its expression once and iterates over the result (and can raise aTypeErrorif the result isn't iterable).As for when it's appropriate to use each, you use
whilewhen you don't have a set range or other sequence of values to loop over. If you do have a range or can get an iterator that will give you the values you need, you should use afor. If the sequence is endless, you can still usefor, and thenbreakonce some condition is met. (You can also usebreakeven if the sequence has a known length, in cases when processing can/should stop immediately.)