Programming repeating algorithms: the while statement
for is handy when the number of repetitions is known beforehand; if it is unknown, while is used. It is written while condition: with the loop body on the next line indented by 4 spaces. Python first checks the condition: if it is True the body is run and it goes back to the condition, if it is False the loop ends; if the condition is False from the very start the body does not run even once. So the loop variable must be given a starting value before the loop and be changed in the body: i += 1 or typing a new number. If the condition never becomes False, the loop goes on forever; in IDLE it can be stopped with the Ctrl + C keys. while True: is also an infinite loop. Do not write an infinite loop on purpose; if you made one by mistake, stop it.
A pupil practising throws into a basket kept throwing until the ball went in. Nobody knew in advance how many throws it would take, so the rule was “repeat until it goes in”, the idea behind a while loop.
Game developers, engineers and programmers repeat while a condition holds when the number of repeats is not known in advance.
On paper write the rule “I read one page a day until the book is finished”. Explain which condition stops it and why.
1i = 1 2while i <= 5: 3 print(i, end=" ") 4 i += 1 5 6s = 0 7n = int(input()) 8while n != 0: 9 s += n 10 n = int(input()) 11print(s)
1 2 3 4 5 20
1p = 1 2while p < 100: 3 print(p, end=" ") 4 p *= 2
1 2 4 8 16 32 64
“Watch the condition”: the group draws a trace table of a while program on the board (step, variable values, condition) and runs it by hand; then it compares with the result in IDLE.
1i = 10 2while i > 0: 3 i -= 3
1i = 1 2while i < 5: 3 print(i)