NanoPy #3

Some Python stretching exercises

Python is a programming language, but python is a program that interprets and executes statements written in the Python language. The python interpreter can be used to run pre-existing source code (typically generated within a text editor), to execute statements interactively, or to do a mixture of both. Type "python" at the command prompt to start up the interpreter:

% python
Python 2.3.4 (#2, Jul  5 2004, 09:15:05) 
[GCC 3.3.4 (Debian 1:3.3.4-2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

>>> print 2+2
4

>>> print [1,2,3]+[4,5,6] 
[1, 2, 3, 4, 5, 6]

# these are builtin objects and operations; where do they come from?

>>> dir()
['__builtins__', '__doc__', '__name__']
>>> help(dir) 
Help on built-in function dir:

dir(...)
    dir([object]) -> list of strings
    
    Return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it:
    
    No argument:  the names in the current scope.
    Module object:  the module attributes.
    Type or class object:  its attributes, and recursively the attributes of
        its bases.
    Otherwise:  its attributes, its class's attributes, and recursively the
        attributes of its class's base classes.

>>> print __doc__
None
>>> print __name__
__main__
>>> print __builtins__
<module '__builtin__' (built-in)>

# __builtins__ is a module; let's see what's inside it

>>> dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

# try executing some builtin functions
>>> print len([1,2,3])
3
>>> print type(2)
<type 'int'>
>>> print range(0,5)
[0, 1, 2, 3, 4]
>>> help(range) # if you don't know how range behaves

>>> print x
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'x' is not defined

>>> dir()
['__builtins__', '__doc__', '__name__']

# let's assign x a value 
>>> x = 3

>>> dir()
['__builtins__', '__doc__', '__name__', 'x']

>>> print x
3

# let's print a random integer between 0 and 10
>>> print randint(0,10)
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'randint' is not defined

# let's import the random module

>>> import random
>>> dir()
['__builtins__', '__doc__', '__name__', 'random', 'x']
>>> print random
<module 'random' from '/usr/lib/python2.3/random.pyc'>
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'Random', 'SG_MAGICCONST', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', 'betavariate', 'choice', 'cunifvariate', 'expovariate', 'gammavariate', 'gauss', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'stdgamma', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random)
# type q to exit

>>> print random.randint(0,10)
2

# let's calculate the cosine of a number
>>> print cos(3.14159)
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'cos' is not defined
>>> import math	
>>> print math.cos(3.14159)
-0.999999999996

>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>> help(math)
# type q to exit

# let's define a new function
>>> def add(x, y):
...    return x+y
...    <enter>

>>> print add(2,2)
4
>>> print add([1,2,3], [4,5,6])
[1, 2, 3, 4, 5, 6]
>>> dir()
['__builtins__', '__doc__', '__name__', 'add', 'math', 'random', 'x']
>>> print type(add)
<type 'function'>

When you type

% python -i SmallWorldNetwork.py

you are bringing everything defined and/or accessible in SmallWorldNetwork.py into the __main__ namespace, e.g.,

>>> dir()
['CircleNetworkGraphics', 'Numeric', 'UndirectedGraph', '__builtins__', '__doc__', 
'__file__', '__name__', 'matplot', 'os', 'random', 'testgraph', 'testplot']

Alternatively, if you type

% python
>>> import SmallWorldNetwork

then everything defined there will be accessible as

SmallWorldNetwork.someobject, e.g.,
SmallWorldNetwork.UndirectedGraph, or
SmallWorldNetwork.CircleNetworkGraphics

Programs are composed of modules, and modules are namespaces