20130111
We concluded our look at fundamental control structures in Python with the while loop. Whereas a for loop iterates through the values of a list (such as a range object),
a while loop repeats as long as some test is passed.
x = 1
while x < 10:
print x
x = x * 2
This will print
1
2
4
8
When
x is assigned the next value in sequence, i.e. 16, the test will fail
when we go back to the top of the loop, so the loop will not be
executed again.
Note that it is possible to create a while loop that never terminates:
x = 1
while x > 0:
print x
x = x * 2
We generally try to avoid this.
There
are other techniques for controlling the flow of program execution but
in the 1930's Alonzo Church and Alan Turing, working independently,
both proved what has come to be called
the Church-Turing Thesis,
which says that any algorithm can be written using just sequence,
selection and repetition. For this reason computer languages that
provide these are sometimes
referred to as computationally complete.
We
used the Collatz Conjecture as the starting point for a programming
exercise to combine the concepts seen so far. Please see the
uploaded Python program.