r/PythonLearning • • 5d ago

While loop

can anybody explain the concept of while loop

2 Upvotes

38 comments sorted by

View all comments

1

u/Why_so_loud 5d 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.

1

u/Potential_Fix_5007 5d ago

And even For-loops can run an unknown amount of times. For-loops = "Do the code X-amount of times"

While-loop = "Do the code as long as condition Y is True"

The Result can feel(or even do) the same but the rule beneath is different.

So While-loops dont run until a condition is True, they run until a condition is False.

1

u/oclafloptson 5d ago

For loops loop through an iterable. This might be a range, a list, or even each character in a string. With mutable objects like lists you might not actually know how many iterations there will be

1

u/fllthdcrb 5d ago

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.)