01 / 07
Loops, and where your data lives
INPUT · Slides
Repeating while a condition holds
02 / 07
The shape of while
Write a condition after while and close the line with :. Indent the body underneath. So far it is the image of if.
The difference is that when the body finishes, it comes back round to the condition. While the condition holds, it goes again, as many times as it takes.
number = 0while number < 3: print(number) number += 1Result
0 1 2
03 / 07
Moving on is your job
for had the next value ready for you. while does nothing of the sort.
The number += 1 in the example above is that job of moving on. Leave that line out and the condition holds for ever, so the program never finishes.
Alarming, but we will do it deliberately in the next lesson.
04 / 07
The condition is a condition for carrying on
What goes after while is not the condition for stopping but the condition for carrying on. That is easy to read the wrong way round.
while number < 3: says "carry on while number is under 3". The moment number becomes 3 the condition fails and the loop is left behind.
Look at number afterwards and you will see it has landed on the first value past the condition.
number = 0while number < 3: number += 1print(number)Result
3
05 / 07
Sometimes it does not run at all
The condition is looked at before the body runs. So if it does not hold to begin with, the body never runs once.
It is not an error; it is passed over quietly. Just like an if whose condition did not hold.
number = 10while number < 3: print(number) number += 1print("done")Result
done
06 / 07
Choosing between for and while
How do you pick between the two? There is only this much to it.
- the count, or the things in a row, is settled …
for - the end is decided by a condition …
while
"Three times" or "everything in the list" means for. "Until the money runs out" or "until an answer comes" means while.
If you cannot decide, take for. A for is bound to finish, which makes it the safer of the two.
07 / 07
while can build a total too
Set the container up outside, add into it inside. The shape you learned with for works unchanged with while.
The one difference is that you move the advancing variable along yourself. In the example below number does the advancing and total does the collecting.
number = 1total = 0while number <= 5: total += number number += 1print(total)Result
15