Python programs, as we've seen, consist of a series of statements, each on its own line. We've seen the following statement types:
statement type | code example |
assignment statement | sentence = 'hello world' |
function call | print(sentence) |
if statement |
if sentence == 'friend:' |
for statement |
for letter in sentence: |
The while
statement is another useful statement,
which combines the looping capability of a for
with
the conditional capability of an if
. In a program, it looks
very much like an if
statement:
num = 1
while num < 10:
num = num * 2
print(num)
The difference is that with an if
, the computer executes
the body once and then continues; but with a while
, it repeats the body until the condition no longer holds.
In this example, the computer:
num
to 1 at the beginning.
num
is below 10; since it is, it executes the body, changing num
to 2.
num
is below 10; since it still is, it executes the body again, changing num
to 4.
num
is still below 10, and so it changes num
to 8.
num
is still below 10, and so it changes num
to 16.
num
is not less than 10 anymore, so it finally executes statements following the body. In this case, it's just the print
call, which displays 16 on the screen.Another example: A program that reads integers from the user until reading 0, at which point it displays the sum of the integers before the 0.
total = 0
num = int(input())
while num != 0:
total = total + num
num = int(input())
print(total)
This program reads a number num
from the user, adding it into total
and then reading another number num
from the user until the user finally types 0. If the user enters 5, 6, 2, then 0,
then total
would see 5, then 6, then 2 added into it, so total
ends up at 13, which the computer then displays.
With the while
loop, it's worth keeping in mind that the
condition is checked only after each iteration completes.
For example, suppose we add “print(num)
” to the end of
the body.
while num != 0:
total = total + num
num = int(input())
print(num)
This displays each number as it is read (except the first, which is read outside the loop). When the user finally enters 0, the computer still
executes “print(num)
”, displaying 0, before realizing that num
is now 0 and so it should not execute the loop's body again.