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

(singke) #1

As you can see, the data from the list is processed in the order in which it was placed in the data list.
Python has no complaints in processing this list. It simply follows the order of the list.


By the Way: Spaces in a Data List
You are not limited in terms of the number of spaces you can put between a comma and
a number in the data list. The data list [1, 5, 15, 9] is legal in a for loop.
However, that is poor form. It is best to put only one space between a comma and the
next data item in a data list.

Assigning Data Types from a List


Python behaves as you would expect it to with data types in for loops. In Listing 7.6, you can see
that Python assigns the data type int (integer) to the variable the_number as it assigns each data
list number to the variable.


LISTING 7.6 Data Types of Numbered Lists


Click here to view code image


>>> for the_number in [1, 5, 15, 9]:
... print (the_number)
... type (the_number)
...
1
<class 'int'>
5
<class 'int'>
15
<class 'int'>
9
<class 'int'>
>>>

Python also changes the data type, as needed, in the assignment (see Listing 7.7). For example,
changing the integer 5 to a floating-point number 5.5 causes the data type to be changed as well.


LISTING 7.7 Changing Data Type


Click here to view code image


>>> for the_number in [1, 5.5, 15, 9]:
... print (the_number)
... type (the_number)
...
1
<class 'int'>
5.5
<class 'float'>
15
<class 'int'>
9
Free download pdf