Page 63 -
P. 63
loop around
Loops let you run the same piece
of code over and over again
Programs often need to keep running the same piece of code
many times. In addition to branches, programming languages also
provide loops.
Loops are a little like branches. Just like branches, loops have a
condition (the loop condition) that is either true or false. Also,
like the if part of branches, if the loop condition is true, then
a loop will run a given piece of code. For a branch, this code is
called the body. For a loop, it’s called the loop body.
answer =
input("Are
The “loop body”
we there?")
When the program first reaches
the loop, it checks the value
of the loop condition before If the loop condition is
deciding what to do next. the code in the loop body.
true, the program runs
print
answer="no"
("We’re
answer==“no”? there!")
FALSE
At the end of the loop, the program
will go back to the start of the loop
and check the condition again...
The big difference between a loop and a branch is how many
times it runs the code associated with it. A branch will run its code
only once. But a loop will run the loop body, then check the loop
condition again and, if it’s still true, it will run the loop body again.
And again. And again. In fact, it will keep running the loop body
until the loop condition becomes false.
28 Chapter 1