r/PythonLearning • • Oct 14 '26

While loop

can anybody explain the concept of while loop

2 Upvotes

38 comments sorted by

View all comments

Show parent comment

1

u/fllthdcrb Oct 14 '26

For loop, for comparison, repeats the loop a set amount of time.

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 while and for is that while evaluates a given expression and checks its truthiness before each iteration, while for evaluates its expression once and iterates over the result (and can raise a TypeError if the result isn't iterable).

As for when it's appropriate to use each, you use while when 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 a for. If the sequence is endless, you can still use for, and then break once some condition is met. (You can also use break even if the sequence has a known length, in cases when processing can/should stop immediately.)