Now to totally blow your mind with a new loop, the while-loop. A while-loop will keep executing the code block under it as long as a boolean expression is True.
Wait, you have been keeping up with the terminology right? That if we write a line and end it with a : (colon) then that tells Python to start a new block of code? Then we indent and that's the new code. This is all about structuring your programs so that Python knows what you mean. If you do not get that idea then go back and do some more work with if-statements, functions, and the for-loop until you get it.
Later on we'll have some exercises that will train your brain to read these structures, similar to how we burned boolean expressions into your brain.
Back to while-loops. What they do is simply do a test like an if-statement, but instead of running the code block once, they jump back to the "top" where the while is, and repeat. It keeps doing this until the expression is False.
Here's the problem with while-loops: Sometimes they do not stop. This is great if your intention is to just keep looping until the end of the universe. Otherwise you almost always want your loops to end eventually.
To avoid these problems, there's some rules to follow:
In this exercise, you will learn the while-loop by doing the above three things:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | i = 0
numbers = []
while i < 6:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
|
$ python ex33.py
At the top i is 0
Numbers now: [0]
At the bottom i is 1
At the top i is 1
Numbers now: [0, 1]
At the bottom i is 2
At the top i is 2
Numbers now: [0, 1, 2]
At the bottom i is 3
At the top i is 3
Numbers now: [0, 1, 2, 3]
At the bottom i is 4
At the top i is 4
Numbers now: [0, 1, 2, 3, 4]
At the bottom i is 5
At the top i is 5
Numbers now: [0, 1, 2, 3, 4, 5]
At the bottom i is 6
The numbers:
0
1
2
3
4
5
If at any time that you are doing this it goes crazy (it probably will), just hold down CTRL and hit c (CTRL-c) and the program will abort.