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

Exercises

  1. Basics, import. With your favorite text editor, write a Python module called mymod.py, which exports three top-level names:

    • A countLines(name) function that reads an input file and counts the number of lines in it (hint: file.readlines() does most of the work for you)

    • A countChars(name) function that reads an input file and counts the number of characters in it (hint: file.read() returns a single string)

    • A test(name) function that calls both counting functions with a given input filename

    A filename string should be passed into all three mymod functions. Now, test your module interactively, using import and name qualification to fetch your exports. Does your PYTHONPATH include the directory where you created mymod.py ? Try running your module on itself: e.g., test("mymod.py"). Note that test opens the file twice; if you’re feeling ambitious, you might be able to improve this by passing an open file object into the two count functions.

  2. from/from. Test your mymod module from Exercise 1 interactively, by using from to load the exports directly, first by name, then using the from* variant to fetch everything.

  3. __main__. Now, add a line in your mymod module that calls the test function automatically only when the module is run as a script. Try running your module from the system command line; then import the module and test its functions interactively. Does it still work in both modes?

  4. Nested imports. Finally, write a second module, myclient.py, which imports mymod and tests its ...

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