Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python
  1. Coding basic loops. If 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 = x + ord(c)
    ...
    >>> x
    433
    
    >>> x = []
    >>> for c in S: x.append(ord(c))
    ...
    >>> x
    [115, 112, 97, 109]
    
    >>> map(ord, S)
    [115, 112, 97, 109]
  2. Backslash characters. The example prints the bell character (\a) 50 times; assuming your machine can handle it, you’ll get a series of beeps (or one long tone, if your machine is fast enough). Hey—we warned you.

  3. Sorting dictionaries. Here’s one way to work through this exercise; see Chapter 2 if this doesn’t make sense:

    >>> 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 = D.keys()
    >>> keys.sort()
    >>> for key in keys:
    ...     print key, '=>', D[key]
    ...
    a => 1
    b => 2
    c => 3
    d => 4
    e => 5
    f => 6
    g => 7
  4. Program logic alternatives. Here’s how we coded the solutions; your results may vary a bit.

    1. 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 = i+1
      else:
          print X, 'not found'
    2. 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'
    3. 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'
    4. X = 5 L = [] for i in range(7): L.append(2 ** i) print L if (2 ** X) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata