# pydemo1.py David MacQuigg ece175 5/2/08 '''Python demo program This is the "docstring" for module pydemo1. It is a multi-line string, delimited by triple quotes. Docstrings are used by the 'help' utility to generate a summary. Try help(pydemo1). For clarity, we will put a ~ on the end quote. ~ ''' ''' Python is an "object-oriented" language. Everything is an object (but not to an extreme:>). [1] Yes, even a simple integer has a bunch of "moving parts"! [2] ~ ''' # def addem(a, b): '''Return the sum of objects a and b. >>> addem(1, 2) # always add a few simple "doctests" 3 >>> addem('spam', 'eggs') # use examples that explain the function [3] 'spameggs' ''' return a + b # The 'add' operator is "polymorphic". It can handle any # # objects than "know how to add". ''' Lists are common objects in Python. They are like arrays, but much more versatile. ~ ''' list1 = [1, 2, 3.1, 'abc'] # a list with 2 integers, a float and a string list1.append(addem) # 'append' is a method of list objects # functions can be passed just like any object ''' >>> list1 [1, 2, 3.1, 'abc', ] >>> list1[4] ~ ''' from doctest import testmod # the testmod function from module doctest testmod(verbose=True) # run it on the current module ''' Notes [1] Stand-alone functions are always there if you need them. i.e. you'll never have to say (-3).__abs__() when abs(-3) will do. In Python, practicality beats purity. [2] Use the directory function dir() whenever you want to find out what is inside an object. >>> dir(list1) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] [3] doctests are primarily for documentation, and should be kept simple. More complex tests can be included in a separate unit_tests() function. ~ '''