Keep going while it's true
A for loop is perfect when you know how many times to repeat. But often you don't. You stir your tea while it is too hot. You walk while you haven't reached home yet.
A while loop checks a condition before every pass. If the condition is true, the lines inside run once, and then the check happens again. As soon as the condition is false, the loop ends. If it is false at the very beginning, the loop never runs at all.
count = 0
while n > 0:
n = n // 2
count = count + 1- n
- 5
- count
- 1
n is 10, which is more than 0, so the loop runs. Halve n: it becomes 5, and the count becomes 1.
Something must change
Be careful with while loops. The loop only ends when its condition becomes false, so something inside the loop has to make that happen.
In the halving loop, each pass makes n smaller, and eventually it reaches 0. If you forgot to change n, the condition would stay true forever, and the computer would run the loop for ever. That is called an infinite loop. Before you run a while loop, ask: what changes on each pass to bring it closer to the end?