Now that you know how to code basic program logic, the following exercises will ask you to implement some simple tasks with statements. Most of the work is in exercise 4, which lets you explore coding alternatives. There are always many ways to arrange statements, and part of learning Python is learning which arrangements work better than others. You’ll eventually gravitate naturally toward what experienced Python programmers call “best practice,” but best practice takes practice.
See Part III in Appendix D for the solutions.
Coding basic loops. This exercise asks you to experiment with for loops.
Write a for loop that prints the ASCII code of each character in a string named S. Use the built-in function ord(character) to convert each character to an ASCII integer. This function technically returns a Unicode code point in Python 3.X, but if you restrict its content to ASCII characters, you’ll get back ASCII codes. (Test it interactively to see how it works.)
Next, change your loop to compute the sum of the ASCII codes of all the characters in a string.
Finally, modify your code again to return a new list that contains the ASCII codes of each character in the string. Does the expression map(ord, S) have a similar effect? How about [ord(c) for c in S]? Why? (Hint: see Chapter 14.)
Backslash characters. What happens on your machine when you type the following code interactively?
for i in range(50):
print('hello %d\n\a' % i)
Beware that if it’s run outside of the IDLE interface this example may beep at you, so you may not want to run it in a crowded room! IDLE prints odd characters instead of beeping—spoiling much of the joke (see the backslash escape characters in Table 7-2).
Sorting dictionaries. In Chapter 8, we saw that dictionaries are unordered collections. Write a for loop that prints a dictionary’s items in sorted (ascending) order. (Hint: use the dictionary keys and list sort methods, or the newer sorted built-in function.)
Program logic alternatives. Consider the following code, which uses a while loop and found flag to search a list of powers of 2 for the value of 2 raised to the fifth power (32). It’s stored in a module file called power.py.
L = [1, 2, 4, 8, 16, 32, 64]
X = 5
found = False
i = 0
while not found and i < len(L):
if 2 ** X == L[i]:
found = True
else:
i = i+1
if found:
print('at index', i)
else:
print(X, 'not found')
C:\book\tests> python power.py
at index 5
As is, the example doesn’t follow normal Python coding techniques. Follow the steps outlined here to improve it (for all the transformations, you may either type your code interactively or store it in a script file run from the system command line—using a file makes this exercise much easier):
First, rewrite this code with a while loop else clause to eliminate the found flag and final if statement.
Next, rewrite the example to use a for loop with an else clause, to eliminate the explicit list-indexing logic. (Hint: to get the index of an item, use the list index method—L.index(X) returns the offset of the first X in list L.)
Next, remove the loop completely by rewriting the example with a simple in operator membership expression. (See Chapter 8 for more details, or type this to test: 2 in [1,2,3].)
Finally, use a for loop and the list append method to generate the powers-of-2 list (L) instead of hardcoding a list literal.
Deeper thoughts:
Do you think it would improve performance to move the 2 ** X expression outside the loops? How would you code that?
As we saw in exercise 1, Python includes a map(function, list) tool that can generate a powers-of-2 list, too: map(lambda x: 2 ** x, range(7)). Try typing this code interactively; we’ll meet lambda more formally in the next part of this book, especially in Chapter 19. Would a list comprehension help here (see Chapter 14)?
Code maintenance. If you haven’t already done so, experiment with making the code changes suggested in this chapter’s sidebar Changing PyDoc’s Colors. Much of the work of real software development is in changing existing code, so the sooner you begin doing so, the better. For reference, my edited copy of PyDoc is in the book’s examples package, named mypydoc.py; to see how it differs, you can run a file compare (fc on Windows) with the original pydoc.py in 3.3 (also included, lest it change radically in 3.4 as the sidebar describes). If PyDoc is more easily customized by the time you read these words, customize colors per its current convention instead; if this involves changing a CSS file, let’s hope the procedure will be well documented in Python’s manuals.