26.8. Control Structures

Like many other languages, Python supports many different control structures that can be used to execute particular blocks of code based on decisions or repeat blocks of code while a particular condition is true. The following sections cover the various control structures available in Python.

26.8.1. While Loop

The while loop executes one or more lines of code while a specified expression remains true. The expression is tested prior to execution of the code stanza and again when the flow returns to the top of the stanza. This loop has the following syntax:

while expression;
  executeMe     #executes if the while expression evaluates to True.

Because the expression is evaluated at the beginning of the loop, the statement(s) will not be executed at all if the expression evaluates to false at the beginning of the loop. For example, the following loop will execute 20 times, each iteration of the loop incrementing x = 20:

x = 0;
while x <= 20
  x += 1;  # increment x if the while expression evaluates to True.

26.8.2. For Loop

The Python for loop is a bit different than the same loop in C or Perl. Whereas these languages execute their loop based on the specified step and halting condition, in Python the for loop iterates its loop over a sequence such as a list or a string. The statement(s) are executed a specific number of times depending on the number of members in the sequence or the range of values passed to it:

>>> for each in ['first.txt','second.txt','third.txt','fourth.txt']: ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.