Test Your Knowledge: Part II Exercises

This session asks you to get your feet wet with built-in object fundamentals. As before, a few new ideas may pop up along the way, so be sure to flip to the answers in Appendix B when you’re done (or when you’re not, if necessary). If you have limited time, I suggest starting with exercises 10 and 11 (the most practical of the bunch), and then working from first to last as time allows. This is all fundamental material, though, so try to do as many of these as you can.

 

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

 
  1. The basics. Experiment interactively with the common type operations found in the various operation tables in this part of the book. To get started, bring up the Python interactive interpreter, type each of the following expressions, and try to explain what’s happening in each case. Note that the semicolon in some of these is being used as a statement separator, to squeeze multiple statements onto a single line: for example, X=1;X assigns and then prints a variable (more on statement syntax in the next part of the book). Also remember that a comma between expressions usually builds a tuple, even if there are no enclosing parentheses: X,Y,Z is a three-item tuple, which Python prints back to you in parentheses.

    2 ** 16
    2 / 5, 2 / 5.0

    "spam" + "eggs"
    S = "ham"
    "eggs " + S
    S * 5
    S[:0]
    "green %s and %s" % ("eggs", S)
    'green {0} and {1}'.format('eggs', S)

    ('x',)[0]
    ('x', 'y')[1]

    L = [1,2,3] + [4,5,6]
    L, L[:], L[:0], L[−2], L[−2:]
    ([1,2,3] + [4,5,6])[2:4]
    [L[2], L[3]]
    L.reverse(); L
    L.sort(); L
    L.index(4)

    {'a':1, 'b':2}['b']
    D = {'x':1, 'y':2, 'z':3}
    D['w'] = 0
    D['x'] + D['w']
    D[(1,2,3)] = 4
    list(D.keys()), list(D.values()), (1,2,3) in D

    [[]], ["",[],(),{},None]

  2. Indexing and slicing. At the interactive prompt, define a list named L that contains four strings or numbers (e.g., L=[0,1,2,3]). Then, experiment with some boundary cases; you may not ever see these cases in real programs, but they are intended to make you think about the underlying model, and some may be useful in less artificial forms:
    1. What happens when you try to index out of bounds (e.g., L[4])?
    2. What about slicing out of bounds (e.g., L[−1000:100])?
    3. Finally, how does Python handle it if you try to extract a sequence in reverse, with the lower bound greater than the higher bound (e.g., L[3:1])? Hint: try assigning to this slice (L[3:1]=['?']), and see where the value is put. Do you think this may be the same phenomenon you saw when slicing out of bounds?
  3. Indexing, slicing, and del. Define another list L with four items, and assign an empty list to one of its offsets (e.g., L[2]=[]). What happens? Then, assign an empty list to a slice (L[2:3]=[]). What happens now? Recall that slice assignment deletes the slice and inserts the new value where it used to be.
    The del statement deletes offsets, keys, attributes, and names. Use it on your list to delete an item (e.g., del L[0]). What happens if you delete an entire slice (del L[1:])? What happens when you assign a nonsequence to a slice (L[1:2]=1)?
  4. Tuple assignment. Type the following lines:

    >>> X = 'spam'
    >>> Y = 'eggs'
    >>> X, Y = Y, X

    What do you think is happening to X and Y when you type this sequence?
  5. Dictionary keys. Consider the following code fragments:

    >>> D = {}
    >>> D[1] = 'a'
    >>> D[2] = 'b'

    You’ve learned that dictionaries aren’t accessed by offsets, so what’s going on here? Does the following shed any light on the subject? (Hint: strings, integers, and tuples share which type category?)

    >>> D[(1, 2, 3)] = 'c'
    >>> D
    {1: 'a', 2: 'b', (1, 2, 3): 'c'}

  6. Dictionary indexing. Create a dictionary named D with three entries, for keys 'a', 'b', and 'c'. What happens if you try to index a nonexistent key (D['d'])? What does Python do if you try to assign to a nonexistent key 'd' (e.g., D['d']='spam')? How does this compare to out-of-bounds assignments and references for lists? Does this sound like the rule for variable names?
  7. Generic operations. Run interactive tests to answer the following questions:
    1. What happens when you try to use the + operator on different/mixed types (e.g., string + list, list + tuple)?
    2. Does + work when one of the operands is a dictionary?
    3. Does the append method work for both lists and strings? How about using the keys method on lists? (Hint: what does append assume about its subject object?)
    4. Finally, what type of object do you get back when you slice or concatenate two lists or two strings?
  8. String indexing. Define a string S of four characters: S = "spam". Then type the following expression: S[0][0][0][0][0]. Any clue as to what’s happening this time? (Hint: recall that a string is a collection of characters, but Python characters are one-character strings.) Does this indexing expression still work if you apply it to a list such as ['s', 'p', 'a', 'm']? Why?
  9. Immutable types. Define a string S of four characters again: S = "spam". Write an assignment that changes the string to "slam", using only slicing and concatenation. Could you perform the same operation using just indexing and concatenation? How about index assignment?
  10. Nesting. Write a data structure that represents your personal information: name (first, middle, last), age, job, address, email address, and phone number. You may build the data structure with any combination of built-in object types you like (lists, tuples, dictionaries, strings, numbers). Then, access the individual components of your data structures by indexing. Do some structures make more sense than others for this object?
  11. Files. Write a script that creates a new output file called myfile.txt and writes the string "Hello file world!" into it. Then write another script that opens myfile.txt and reads and prints its contents. Run your two scripts from the system command line. Does the new file show up in the directory where you ran your scripts? What if you add a different directory path to the filename passed to open? Note: file write methods do not add newline characters to your strings; add an explicit \n at the end of the string if you want to fully terminate the line in the file.