Exercises

Now that you know how to code basic program logic, this session asks 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.

  1. Coding basic loops.

    1. 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 (test it interactively to see how it works).

    2. Next, change your loop to compute the sum of the ASCII codes of all characters in a string.

    3. Finally, modify your code again to return a new list that contains the ASCII codes of each character in the string. Does this expression have a similar effect—map(ord, S)? (Hint: see Chapter 4.)

  2. 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

    Warning: this example beeps at you, so you may not want to run it in a crowded lab (unless you happen to enjoy getting lots of attention). Hint: see the backslash escape characters in Table 2.6.

  3. Sorting dictionaries. In Chapter 2, 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.

  4. Program logic alternatives. Consider the following code, which uses a while loop and ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.