While Loops
While loops are more general than for-loops. Basically, the same block of statements is repeated
The "while" is a keyword. The condition needs to be something that evaluates to True or False, for example, a Boolean expression. The block of statements is indented as with a for loop. As an aside, Python can be picky about intermingling tabs and spaces. Fortunately, Python-aware editors such as IDLE deal with this very nicely by changing tabs to white spaces.
Because the while loop is only finished when the condition is no longer true, it is possible to write infinite loops. If you have (or suspect) an infinite loop in your executing code, you can stop execution of the program by typing in Control-D or Control-C into the shell.
Breaking out of while loops
Python has two keywords to break out of a while loop. The statement break
terminates immediately the while loop. The rarer statement continue
breaks out of the current iteration and starts again at the beginning of the loop
body (i.e. the indented statement block.) Both statements also work for for-loops.
There is also the possibility to put a else
statement at the same level
as the while
. The statement block in this else
block is
executed whenever the loop terminates normally. This is a pretty confusing feature,
until it isn't. Therefore, it is not part of this class, but eventually, you might
want to learn it when you are no longer a beginning programmer.