Page 127 -
P. 127

files and exceptions


           Identify the code to protect


           In order to plug into the Python exception handling mechanism, take a
           moment to identify the code that you need to protect.




                                                Study your program and circle the line or lines of code that you
                                                think you need to protect. Then, in the space provided, state why.


                          data = open('sketch.txt')


                          for each_line in data:
                                   (role, line_spoken) = each_line.split(':', 1)
                                   print(role, end='')
                                   print(' said: ', end='')
                                   print(line_spoken, end='')

                                                                                     State your reason
                          data.close()
                                                                                     why here.




















           Q:   Something has been bugging me for a while. When the split() method executes, it passes back a list, but the target identifiers

           are enclosed in regular brackets, not square brackets, so how is this a list?

          A: Well spotted. It turns out that there are two types of list in Python: those that can change (enclosed in square brackets) and those that
           cannot be changed once they have been created (enclosed in regular brackets). The latter is an immutable list, more commonly referred
           to as a tuple. Think of tuples as the same as a list, except for one thing: once created, the data they hold cannot be changed under any
           circumstances. Another way to think about tuples is to consider them to be a constant list. At Head First, we pronounce “tuple” to rhyme with
          “couple.” Others pronounce “tuple” to rhyme with “rupal.” There is no clear concensus as to which is correct, so pick one and stick to it.

                                                                                       you are here 4    91
   122   123   124   125   126   127   128   129   130   131   132