[Courses] [python] Lesson 4: Modules and command-line arguments

Monique Y. Mudama monique at bounceswoosh.org
Mon Jul 11 19:56:05 UTC 2011




On Fri, Jul  8 at 13:56, Akkana Peck penned:
> ========================= Homework ============================
> 
> 1. With the little example I gave earlier, the one that used
>    num = int(sys.argv[1]):
>    if you run it and don't give an argument, you'll get an error.
>    Why? Can you think of a way to check whether the user forgot to
>    supply an argument, and print an error message if so?

List index 1 references the second element in the list; there are no
arguments, so there will only be one element, which is the path to the
executable.  You can check it by testing the length of the list - 

if len(sys.argv) != 2:
	usage()
	sys.exit(1)

> 2. Write a program that takes a filename and prints the number of
> lines in the file. (You can check its results with wc -l filename.)


import sys
import os

def usage():
    print "arg1: the path to a file"

if len(sys.argv) != 2:
    usage()
    sys.exit(1)


if not os.path.exists(sys.argv[1]):
    print "file not found"
    sys.exit(1)

words_file = open(sys.argv[1])

line_count = 0

for line in words_file:
    line_count = line_count + 1

print "your file has " + str(line_count) + " lines"

> 3. How would you extend this so that you can count lines in multiple
> files, not just one? So you could say
> $ mywordcounter file1 file2 file3

import sys
import os

def usage():
    print "arg1, arg2, etc: paths to files"

if len(sys.argv) < 2:
    usage()
    sys.exit(1)

def count_lines(filename):
    if not os.path.exists(filename):
        print "file not found: " + filename
        sys.exit(1)

    words_file = open(filename)

    line_count = 0

    for line in words_file:
        line_count = line_count + 1

    print filename + " has " + str(line_count) + " lines"

for filename in sys.argv[1: len(sys.argv)]:
    count_lines(filename)

> 4. Here's a harder problem, an exercise in debugging (which is a big
>    part of programming, sadly):
> 
>    a. Write a program that counts words in a file (or multiple files,
>       if you prefer). Use the same split() and len() you used in
>       lesson 2.

import sys
import os

def usage():
    print "arg1, arg2, etc: paths to files"

if len(sys.argv) < 2:
    usage()
    sys.exit(1)

def count_lines(filename):
    if not os.path.exists(filename):
        print "file not found: " + filename
        sys.exit(1)

    words_file = open(filename)

    word_count = 0

    for line in words_file:
        word_count = word_count + len(line.split())

    return word_count

for filename in sys.argv[1: len(sys.argv)]:
    print count_lines(filename)

> 
>    b. Compare the number of words from your program to what wc -w gives.
>       (If you're on a platform that doesn't have wc, run it on a small
>       file and count by hand.) Are the answers the same?

I didn't expect them to be - but they actually are. Even though I'm using my code 
as input, which I would expect to contain all sorts of edge cases.

> 
>    c. Here's the debugging part: why aren't they the same?
>       (You don't have to fix it: just figure out the problem.)

I was going to guess punctuation and newlines, but I'm not seeing any problems.

>       Hint: if you're splitting each line into a list, try printing
>       the list to see what's in it. In python, if you have a list
>       called words, you can just say print words -- you don't have to
>       do anything fancy like you would in some languages.
> 
>    d. OPTIONAL, harder: fix the problems and make your word count
>       program give the same answer as wc -w.
> 
>       Hint 1: one Python function that will come in handy is strip():
>       it strips off any leading and trailing spaces. So if you have
>       a string s = "     hello, world     ", then s.strip() would
>       give you "hello, world".
> 
>       By the way, I haven't mentioned Python's documentation, but
>       most Python modules have excellent online docs. Here's strip():
>       http://docs.python.org/library/string.html#string.strip
> 
>       Hint 2: If you're inside a loop, say, looping over lines, and
>       you decide you don't care about this line, you can skip to the
>       next one by saying:
>           continue
>       For instance, in a loop where you don't care about negative numbers:
>       for i in list_of_numbers :
>           if i < 0 :
>               continue
>           do_stuff_for_positive_numbers(i)
> 
>       You can break out of a loop completely with: break
> 
>       Don't drive yourself too crazy trying to get an exact match
>       with wc. There are some special cases where splitting at spaces
>       might not give the same answer as wc -w, and there are some
>       other Python modules (specifically re, regular expressions)
>       that can do a better job. The purpose of this exercise is to
>       give you a taste of debugging, fixing problems as you find them
>       and thinking about what special cases might arise.
> _______________________________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses
> 

-- 
monique


More information about the Courses mailing list