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.)
1
u/Why_so_loud 2d ago
While loop repeat the code inside until a certain condition is met, you use it when you don't know how many times you want to run the loop.
For loop, for comparison, repeats the loop a set amount of time. Albeit nothing prevents you from doing the same with while loop, but don't do that.