Exercises
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, usingimport
and name qualification to fetch your exports. Does yourPYTHONPATH
include the directory where you createdmymod.py
? Try running your module on itself: e.g.,test("mymod.py")
. Note thattest
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.from/from. Test your
mymod
module from Exercise 1 interactively, by usingfrom
to load the exports directly, first by name, then using thefrom*
variant to fetch everything.__main__. Now, add a line in your
mymod
module that calls thetest
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?Nested imports. Finally, write a second module, myclient.py, which imports
mymod
and tests its ...
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.