Part III, Statements and Syntax

See Test Your Knowledge: Part III Exercises in Chapter 15 for the exercises.

 

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

 
  1. Coding basic loops. As you work through this exercise, you’ll wind up with code that looks like the following:

    >>> S = 'spam'
    >>> for c in S:
    ...     print(ord(c))
    ...
    115
    112
    97
    109

    >>> x = 0
    >>> for c in S: x += ord(c)             # Or: x = x + ord(c)
    ...
    >>> x
    433

    >>> x = []
    >>> for c in S: x.append(ord(c))
    ...
    >>> x
    [115, 112, 97, 109]

    >>> list(map(ord, S))                   # list() required in 3.0, not 2.6
    [115, 112, 97, 109]

  2. Backslash characters. The example prints the bell character (\a) 50 times; assuming your machine can handle it, and when it’s run outside of IDLE, you may get a series of beeps (or one sustained tone, if your machine is fast enough). Hey—I warned you.
  3. Sorting dictionaries. Here’s one way to work through this exercise (see Chapter 8 or Chapter 14 if this doesn’t make sense). Remember, you really do have to split up the keys and sort calls like this because sort returns None. In Python 2.2 and later, you can iterate through dictionary keys directly without calling keys (e.g., for key in D:), but the keys list will not be sorted like it is by this code. In more recent Pythons, you can achieve the same effect with the sorted built-in, too:

    >>> D = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7}
    >>> D
    {'f': 6, 'c': 3, 'a': 1, 'g': 7, 'e': 5, 'd': 4, 'b': 2}
    >>>
    >>> keys = list(D.keys())              # list() required in 3.0, not in 2.6
    >>> keys.sort()
    >>> for key in keys:
    ...     print(key, '=>', D[key])
    ...
    a => 1
    b => 2
    c => 3
    d => 4
    e => 5
    f => 6
    g => 7

    >>> for key in sorted(D):              # Better, in more recent Pythons
    ...     print(key, '=>', D[key])

  4. Program logic alternatives. Here’s some sample code for the solutions. For step e, assign the result of 2 ** X to a variable outside the loops of steps a and b, and use it inside the loop. Your results may vary a bit; this exercise is mostly designed to get you playing with code alternatives, so anything reasonable gets full credit:

    # a

    L = [1, 2, 4, 8, 16, 32, 64]
    X = 5

    i = 0
    while i < len(L):
        if 2 ** X == L[i]:
            print('at index', i)
            break
        i += 1
    else:
        print(X, 'not found')


    # b

    L = [1, 2, 4, 8, 16, 32, 64]
    X = 5

    for p in L:
        if (2 ** X) == p:
            print((2 ** X), 'was found at', L.index(p))
            break
    else:
        print(X, 'not found')


    # c

    L = [1, 2, 4, 8, 16, 32, 64]
    X = 5

    if (2 ** X) in L:
        print((2 ** X), 'was found at', L.index(2 ** X))
    else:
        print(X, 'not found')


    # d

    X = 5
    L = []
    for i in range(7): L.append(2 ** i)
    print(L)

    if (2 ** X) in L:
        print((2 ** X), 'was found at', L.index(2 ** X))
    else:
        print(X, 'not found')


    # f

    X = 5
    L = list(map(lambda x: 2**x, range(7)))      # or [2**x for x in range(7)]
    print(L)                                     # list() to print all in 3.0, not 2.6

    if (2 ** X) in L:
        print((2 ** X), 'was found at', L.index(2 ** X))
    else:
        print(X, 'not found')