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

(singke) #1
interactive shell that you are ready for the loop to be interpreted and the results
displayed. However, in a text editor, this extra press of the Enter key is not needed.

The next “gotcha” is not using commas to separate your numeric data list. In Listing 7.3, you can see
that no error is generated, but this is probably not the result being sought.


LISTING 7.3 Missing Commas in a for Loop Data List


Click here to view code image


>>> for the_number in [12345]:
... print (the_number)
...
12345
>>>

Don’t forget to keep your indentation consistent. If you are using spaces for indenting, then continue to
use exactly the same number of spaces for indentation for each Python statement in the loop. If you are
using tabs for indenting, then continue to use exactly the same number of tabs for indentation. In
Listing 7.4, you can see how Python complains when spaces are used for one indentation and tabs are
used for the other.


LISTING 7.4 Inconsistent Indentation


Click here to view code image


>>> for the_number in [1, 2, 3, 4, 5]:
... print ("Spaces used for indentation")
... print ("Tab used for indentation")
File "<stdin>", line 3
print ("Tab used for indentation")
^
TabError: inconsistent use of tabs and spaces in indentation
>>>

This next item is not really a “gotcha” but a reminder to be aware that the numbers you use in a data
list do not have to be in numeric order. Listing 7.5 shows an example of this.


LISTING 7.5 Non-Numeric Order of Numbered Lists


Click here to view code image


>>> for the_number in [1, 5, 15, 9]:
... print (the_number)
...
1
5
15
9
>>>
Free download pdf