Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
However, in a text editor, you need to remember to tab or space over yourself.

The operation of a for loop is as follows:


The variable in the for construct is assigned the first value in the data list.
The Python statement(s) in the loop is executed and has the option of using the assigned
variable’s value during execution.
Upon completion of the loop’s Python statement(s), the variable is reassigned the next value in
the data list.
The Python statement(s) in the loop is then executed and has the option of using the variable’s
reassigned value during execution.
The for loop continues until all the values have been assigned to the variable and the Python
statement(s) in the loop is executed during each assignment.

Reading about structure is not as helpful as diving into specific examples. The following sections
will help you better understand for loops.


Iterating Using Numeric Values in a List


You can have the for loop iterate through numbers by providing the numbers in a data list, as shown
in Listing 7.1. The only Python statement in this loop is print (the_number), which prints the
current number being used from the data list.


LISTING 7.1 A for Loop


Click here to view code image


>>> for the_number in [1, 2, 3, 4, 5]:
... print (the_number)
...
1
2
3
4
5
>>>

Notice the format of the data list in the for loop construct in Listing 7.1. The numbers are contained
within two square brackets, and the numbers are separated with commas. The variable
the_number is assigned a number in the data list, starting with the first number ( 1 ). After the
Python statement print (the_number) within the for loop is completed, the variable,
the_number, is then assigned to the next number in the data list. Figure 7.1 shows stepping through
the for loop in this manner.

Free download pdf