Please send questions to st10@humboldt.edu .
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) 
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "copyright", "credits" or "license()" for more information.

IDLE 1.2      
>>> import sys
>>> sys.path.append("/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08")

>>> # you can insert documentation into a module
>>> #    so that certain Python tools will display
>>> #    it on request...
>>> # PyDoc is the tool that does this;
>>> #    it is used by the help() function inside a
>>> #    Python interpreter,
>>> #    and by pydoc at the command line,
>>> #    (and I think more, also)

>>> # SO -- where do you put info so PyDoc will find it?
>>> #    if you put a string as the first executable line
>>> #    in a file/module --- that will be considered the
>>> #    docstring for that module;
>>> # IF you put a string as the first executable line in
>>> #    a function --- that will be considered the
>>> #    docstring for that function

>>> # so - consider revised version of lect07.py... (posted along with
    #    this session)

>>> # let's import it

>>> import lect07

>>> # now: help(lect07), I'll see a nicely-formatted page
>>> #    making use of those docstrings I've added to lect07.py

>>> help(lect07)
Help on module lect07:

NAME
    lect07

FILE
    /Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/lect07.py

DESCRIPTION
    lect07.py
    contains examples of functions making use of file input/output

FUNCTIONS
    letter_freq_file(input_name)
        shows to the screen a simple ASCII horizontal "bar chart" of
        all of the letters within file <input_name>
    
    pig_latin_file(input_name, output_name)
        write pig-latin versions of all the lines of file <input_name>
        into file <output_name> - nukes any previous contents of
        <output_name>!


>>> # I can also use help with a function name to see the
>>> #    docstring for that function (if it exists)

>>> help(lect07.pig_latin_file)
Help on function pig_latin_file in module lect07:

pig_latin_file(input_name, output_name)
    write pig-latin versions of all the lines of file <input_name>
    into file <output_name> - nukes any previous contents of
    <output_name>!

>>> help(lect07.letter_freq_file)
Help on function letter_freq_file in module lect07:

letter_freq_file(input_name)
    shows to the screen a simple ASCII horizontal "bar chart" of
    all of the letters within file <input_name>

>>> # even with no docstrings, you can still see what functions are
>>> #    in a module pretty nicely with help function...
>>> # (but this looks better if you use descriptive parameter names! 8-) )

>>> import hw4

>>> help(hw4)
Help on module hw4:

NAME
    hw4

FILE
    /Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/hw4.py

DESCRIPTION
    # hw4.py
    # by: Sharon Tuttle
    # last modified: 10-10-06

FUNCTIONS
    keep_letters(aWord)
    
    pig_latin(word)
    
    pig_list(aString)
    
    pig_string(aString)
    
    starts_with_vowel(word)
    
    strip_punct(aString)

>>> # AT THE UNIX COMMAND LINE,
>>> #    pydoc module-name-with-NO-.py
>>> # ...will give you a PyDoc description of your file
>>> #    outside of the python interpreter, also

>>> # TOPIC #2 - intro to EXCEPTIONS in Python

>>> # We know that we get errors when we do inappropriate
>>> #    things in Python...

>>> 3 + 'harry'

Traceback (most recent call last):
  File "<pyshell#48>", line 1, in <module>
    3 + 'harry'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

>>> # when Python detects an error at run-time, it raises
>>> #    exception --- above, a TypeError exception was raised

>>> # above, you see the default exception handling behavior...
>>> # (the program stops, an error message is printed)

>>> # BUT - what if you'd like to do something DIFFERENT for
>>> #    a particular exception?

>>> # you can:
>>> # *   wrap the statement that might raise an exception
>>> #     in a try-statement;
>>> # *   use the except: part of the try statement to then
>>> #     say what to do if a particular exception is raised
>>> #     in the wrapped statements...

>>> def fetcher(obj, index):
	return obj[index]

>>> food = 'spam'

>>> fetcher(food, 2)
'a'

>>> fetcher(['a', 'b', 'c', 'd', 'e'], 2)
'c'

>>> fetcher({'a':4, 'b':5}, 'b')
5
>>> fetcher(2, 3)

Traceback (most recent call last):
  File "<pyshell#73>", line 1, in <module>
    fetcher(2, 3)
  File "<pyshell#68>", line 2, in fetcher
    return obj[index]
TypeError: 'int' object is unsubscriptable

>>> fetcher(food, 27)

Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    fetcher(food, 27)
  File "<pyshell#68>", line 2, in fetcher
    return obj[index]
IndexError: string index out of range

>>> try:
	fetcher(food, 27)
except IndexError:
	print "Hey! I got an Index Error!"

	
Hey! I got an Index Error!

>>> try:
	fetcher(food, 27)
except TypeError:
	print "Hey! I got a Type Error!"

	

Traceback (most recent call last):
  File "<pyshell#85>", line 2, in <module>
    fetcher(food, 27)
  File "<pyshell#68>", line 2, in fetcher
    return obj[index]
IndexError: string index out of range

>>> def nicerFetch(item, index):
	try:
		return fetcher(item, index)
	except TypeError:
		print "Hey! I got a Type Error!"
	except IndexError:
		print "Hey! I got an Index Error!"

		
>>> nicerFetch(food, 1)
'p'

>>> nicerFetch(food, 27)
Hey! I got an Index Error!

>>> nicerFetch(2, 3)
Hey! I got a Type Error!

>>> value = nicerFetch(food, 1)

>>> value
'p'

>>> value = nicerFetch(food, 27)
Hey! I got an Index Error!

>>> value

>>> value = nicerFetch(2, 3)
Hey! I got a Type Error!

>>> value

>>> # hey - notice a Python function can return different
>>> #    types for different arguments...!

>>> def sillyExample(value):
	if (type(value) == str):
		return "ok"
	elif type(value) == int:
		return 1
	elif type(value) == bool:
		return True

	
>>> sillyExample(1)
1

>>> sillyExample("howdy")
'ok'

>>> sillyExample(True)
True

>>> sillyExample([1, 2, 3])

>>> # side point: Python doesn't have a case or switch
>>> #    statement; doesn't feel it needs it, with
>>> #    if/elif and dictionary tricks...

>>> branch = {'spam':1.25,
	      'ham': 0.99,
	      'chocolate': 3.25}

>>> print branch.get('spam', 'No good')
1.25

>>> def orderCost():
	item = raw_input("What food would you like? ")
	cost = branch.get(item, "Bad choice!")
	return cost

>>> orderCost()
What food would you like? spam
1.25

>>> orderCost()
What food would you like? chocolate
3.25

>>> orderCost()
What food would you like? Quince
'Bad choice!'

>>> # back to exceptions:
>>> #    you can RAISE an exception with a raise command:

>>> bad = 'uh oh'

>>> try:
	raise bad
except bad:
	print 'got bad'

	

Warning (from warnings module):
  File "__main__", line 2
DeprecationWarning: raising a string exception is deprecated
got bad

>>> # (oops - may want to look up setting a "real" exception
>>> #    value)

>>> type(TypeError)
<type 'type'>

>>> def looky(val):
	if val == 3:
		raise IndexError
	else:
		print "Howdy"

		
>>> looky(4)
Howdy

>>> looky("the rain in spain")
Howdy

>>> looky(3)

Traceback (most recent call last):
  File "<pyshell#174>", line 1, in <module>
    looky(3)
  File "<pyshell#171>", line 3, in looky
    raise IndexError
IndexError

>>> # there are MORE options to go with a try-block
>>> #    than just except (except with diff #'s of values,
>>> #    finally, else... see Python documentation for more

>>> # a few more words about modules...
>>> # *   module is the highest-level program organization
>>> #     unit in Python ("Learning Python", p. 248)
>>> # *   really/fundamentally - a module is a collection of
>>> #     names!!
>>> # *   (we know already) - import lets us fetch a module
>>> #     as a whole...

>>> # WHEN you import a module ---
>>> # *   python FINDS it,
>>> # *   if there's no .pyc for it, it COMPILES it
>>> # *   runs the module's byte code to build its objects

>>> # why don't you put a suffix in the import?
>>> # ...that's on purpose!
>>> # *   because it MIGHT be .py or .pyc
>>> # *   for package imports, there might no suffix;
>>> # *   C extension module has another suffix
>>> # *   a Java class in Jython would another,
>>> # *   a zip file component would have enother
>>> # *   (see "Learning Python", p. 254 for more on this
>>> #     if you'd like)

>>> # that first import step for a module -
>>> #    "python FINDS it" -- isl, of course, a tale by
>>> #    itself;

>>> # note: you CAN'T put path information IN the import
>>> #    statement... BUT,
>>> # it will BUILD a search path... to look for it;
>>> # 1. the home directory of the top-level file
>>> # 2. PYTHONPATH directories (if set)
>>> # 3. standard library directories
>>> # 4. the contents of any .pth files (if present)
>>> #    (a text file that lists, 1 per line, additional
>>> #    directories to search - this text file's name
>>> #    ends in .pth)

>>> # takes the CONCATENATION of all of these paths, and
>>> # creates: a list, named sys.path!

>>> # if you really want to know - at any time - where python
>>> #    is looking for stuff - look at sys.path!
>>> #    (but import sys first - I happened to have done it at the beginning
>>> #    of this session...)

>>> sys.path
['/Users/smtuttle/Documents', '/Applications/MacPython 2.5/IDLE.app/Contents/Resources', '/Applications/MacPython 2.5/IDLE.app/Contents/Resources', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload', '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages', '/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08']

>>> # a prettier way to look at sys.path's paths...

>>> for item in sys.path:
	print item

	
/Users/smtuttle/Documents
/Applications/MacPython 2.5/IDLE.app/Contents/Resources
/Applications/MacPython 2.5/IDLE.app/Contents/Resources
/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload
/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages
/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08

>>> # AHA - there is a way to RE-import a module already imported,
>>> #    if you need to do so (and perhaps don't want to take down a
>>> #    running system) --- the reload function

>>> # first, demonstrate the reason why... tryMe.py originally just has
>>> #    a greeting variable:

>>> import tryMe

>>> help(tryMe)
Help on module tryMe:

NAME
    tryMe

FILE
    /Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/tryMe.py

DATA
    greeting = 'Hello'

>>> # In another window, I add a farewell variable. But, as you see below,
>>> #    importing again has no effect (Python notes it is already loaded,
>>> #    and does nothing...) 

>>> import tryMe

>>> help(tryMe)
Help on module tryMe:

NAME
    tryMe

FILE
    /Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/tryMe.py

DATA
    greeting = 'Hello'

>>> # the reload function WILL force an already-loaded
>>> #    module's code to be REloaded and RErun

>>> reload(tryMe)
<module 'tryMe' from '/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/tryMe.py'>

>>> # NOW can we see tryMe's new greeting variable? Yes!

>>> help(tryMe)
Help on module tryMe:

NAME
    tryMe

FILE
    /Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/tryMe.py

DATA
    farewell = 'Au revoir'
    greeting = 'Hello'

#   yes, the return value here IS a little interesting... 8-)

>>> value = reload(tryMe)
>>> value
<module 'tryMe' from '/Users/smtuttle/Humboldt/to-back-up/f06cis180py/180py_lectures/180py_lect08/tryMe.pyc'>
>>>