12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Part III, Statements and SyntaxSee “Part III Exercises” in Chapter 14 for the exercises.1. Coding basic loops. As you work through this exercise, you’ll wind up with codethat looks like the following:>>> S = 'spam'>>> for c in S:... print ord(c)...11511297109>>> x = 0>>> for c in S: x += ord(c) # Or: x = x + ord(c)...>>> x433>>> 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; assumingyour machine can handle it, and when it’s run outside of IDLE, you may geta series of beeps (or one long tone, if your machine is fast enough). Hey—Iwarned you.3. Sorting dictionaries. Here’s one way to work through this exercise (see Chapter 8if this doesn’t make sense). Remember, you really do have to split up the keysand sort calls like this because sort returns None. In <strong>Python</strong> 2.2 and later, youcan iterate through dictionary keys directly without calling keys (e.g., for key inD:), but the keys list will not be sorted like it is by this code. In more recent<strong>Python</strong>s, 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 = D.keys( )>>> keys.sort( )>>> for key in keys:... print key, '=>', D[key]...654 | Appendix B: Solutions to End-of-Part Exercises

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!