Python Tutorial for CS114

Please send questions or comments to cs114 class account

1. Preliminaries

1.1 Python at Brandeis

For our course, we will use Python 2.2.3. It is available on the following workstations in the Berry Patch:

cleo
iole
penelope
absyrtus
acastas
aeson
alcestis
bia
creusa
dejanira
laertes
pelias
pentheus

The rest of them still run previous python versions. So please avoid using them. Remember that we will NOT accept code that does not run on python 2.2.3.

1.2 Python Documentation and Tutorials

The official Python language website is www.python.org.

The following Python tutorials are available on the web:

  • Python tutorial (v. 2.2.3), from the official www.python.org site.
  • Another minimal crash-course in Python
  • If you need a slow step-by-step introduction to python, you may like to start with the Beginner's Guide or other introductory stuff.

    For general reference you might find especially useful the Python Library Reference (v.2.2.3).

    All Python documentation, along with links to more tutorials, is available at http://www.python.org/doc/.

    You can download a copy to your PC from http://www.python.org/download/

    2. A Quick Intro to Python

    Python is an interpreted, object-oriented language implemented mostly in C/C++. Its clear syntax makes it easy to learn, and an ideal language for scripting and fast code development.

    2.1 Invoking the interpreter

    Python Interactive mode:

    The Python interpreter provides a command-line interface. To access this interactive mode, type python at the prompt on any of the CS machines listed above:

    
    [your_handle@cleo ~]$ python
    Python 2.2.3 (#1, Jun 16 2003, 13:21:11) 
    [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> _
    

    In interactive mode, the interpreter can be used as calculator:

    
    >>> a = 3
    >>> a
    3
    >>> 3*3
    9
    

    To exit from the interpreter: C-d

    How to run Python:

    Files containing python code traditionally have the extension .py. To run a file with your code:

    [yourhandle@cleo ~]$ python <filename>.py


    If you prefer to enter the interactive mode after your file has been executed, use:

    [yourhandle@cleo ~]$ python -i <filename>.py


    In order to access command line arguments, as in:

    [yourhandle@cleo ~]$ python <filename>.py <arg1> <arg2>

    you need to work with the module sys.


    Remember that in order to turn your file into an executable script, you have to modify the permissions appropriately (chmod u+x <filename>), and add the following standard shell instruction to the top of your file:

    #!/usr/bin/python

    To use Python from xemacs:

    Editing a file ending in .py will invoke the Python mode. A couple of useful commands in this mode are:

    2.2 Importing modules

    You can import standard modules or your own files (e.g., myFile.py). To import the whole module:

    
    >>> import string
    >>> import time
    
    
    >>> import myFile
    >>> myFile.myFunction()
    

    To import a particular functions, classes, or variables:

    
    >>> from sys import exit
    >>> exit()
    [yourhandle@cleo ~]$ _
    
    
    >>> from myFile import myFunction
    >>> myFunction()
    
    
    >>> from myFile import MyClass
    >>> a = MyClass()
    >>> a.myMethod()
    

    2.3 Syntax Basics

    Comments start with '#', as in Perl.

    No curly brackets are needed. Only indentation is used to mark blocks:

    
    if a < 0:
        print "a is negative"
    else:
        print "a is non-negative"    
    

    2.4 Variables

    Variables don't have types, so no variable declarations are necessary.

    Numeric types are standard, except long integers have unlimited precision in Python:

    
    >>> a = 44444444444444444422222222222222222444444444444444444L
    >>> a * a
    1975308641975308640000000000000000020246913580246913530864197530864197599999999999999999802469135802469136L
    

    2.5 Built-in Data Types

    Python has the following built-in data types:

    Strings
    Lists
    Tuples
    Dictionaries

    The first 3 types are sequence types, and are basically similar to arrays in other programming languages. Strings are arrays of characters. Tuples and lists are arrays of arbitrary values. Consequently, tuples and lists can be nested. Strings and tuples are immutable, whereas lists are mutable.

    Sequence Types:

    Some examples of each type:
    1. Strings:
      
      >>> a = "There is no \"place\" like home"
      >>> a
      'There is no "place" like home'
      >>> b = "There's no place like home"
      >>> b
      "There's no place like home"
      >>> c = 'There\'s no place like home'
      >>> c
      "There's no place like home"
      

      All standard escape sequences apply to Python strings:

      
      >>> a = "blah\tblah"
      >>> a
      'blah\011blah'
      >>> print a
      blah	blah
      

    2. Lists:
      
      >>> alist = ['There', 'is', 'no', 'place', 'like', 'home']
      >>> blist = ['There', 0.34]
      >>> clist = [['There', 0.34], ['is', 0.57]]
      >>> dlist = [('There', 0.34), ('is', 0.57)]
      
    3. Tuples:
      
      >>> atuple = ('There', 0.34)
      >>> btuple = ('bigram', [('There', 'is'), 0.34])
      

    How can we manipulate sequence types:

    Hash Tables: Dictionaries

    Dictionaries are associative arrays or hashes. Any immutable Python object can be used as a key in a dictionary.

    
    >>> adict = {}
    >>> adict['a'] = 1
    >>> adict
    {'a': 1}
     
    >>> bdict = {"joe": [3.5, 4.34], "kat": [3.45, 4.5]}
    >>> bdict['kat']
    [3.45, 4.5]
    
    Check other possible operations with dictionaries here. And if what you want is to create persistent dictionaries, you have to use the shelve module.

    2.6 Truth Values and Boolean Operations

    The following values are false in Python:

    All other values are true.

    Boolean operations: not, and, or

    
    >>> a = '' 
    >>> b = 32
    >>> a or b
    32
    >>> a or not b
    0
    

    2.7 Comparison operators:

    The standard comparison operators are written the same as in C:

    You can compare sequence objects of the same type (using lexicographic order):

    
    >>> (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
    1
    

    For sequences, there is a membership testing operator in:

    
    >>> b = 32
    >>> b in [21, 32]
    1
    

    2.8 Control Flow

    All the standard loop and conditional constructs are present:

    2.9 Functions

    Functions in Python are defined using the command def:

    >>> def square(x): 
    ...     return x*x
    ... 
    >>> square(3)
    9
    

    Python allows default arguments:

    
    >>> def modsum(a, b, c = 10):
    ...     return (a+b)%c
    ... 
    >>> modsum(22, 33)
    5
    
    >>> modsum(22, 33, 5)
    0
    

    2.10 Classes

    Classes are defined using class. A good programming convention is to name your classes in Upper case:

    
    class MyClass:
    	(class methods...)
    

    Class methods have to state self as its first argument:

    
    >>> class MyClass:
    ...     def myMethod(self):
    ...         print "Hello world!"
    ... 
    >>> b = MyClass()
    >>> b.myMethod()
    Hello world!
    
    Variables can be passed to or set up during class instantiation, using the built-in __init__ method:
    
    >>> class MyClass:
    ...     def __init__(self, y):
    ...             self.x = 3
    ...             self.y = y	
    ...             self.displayCurrentState()
    ...     def displayCurrentState(self):
    ...             print "Current State:", self.x
    ...     def changeState(self):
    ...             self.x = self.x * self.y
    ...             self.displayCurrentState()
    ... 
    >>> c = MyClass(5)
    Current State: 3
    >>> c.changeState()
    Current State: 15
    >>> c.changeState()
    Current State: 75
    >>> c.changeState()
    Current State: 375
    >>> c.changeState()
    Current State: 1875
    >>> c.changeState()
    Current State: 9375
    >>> c.changeState()
    Current State: 46875
    >>> c.changeState()
    

    2.11 Reading and writing files

    1. Printing in Python is easy:
      
      >>> x = 10 * 3.14
      >>> y = 2 * 2
      >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` 
      >>> print s
      The value of x is 31.4, and y is 4
      

      Note that in the above writing `x` is the same as str(x), the latter being an built-in function. So

      
      >>> s = 'The value of x is ' + `x` + ', and y is ' + `y`
      
      is the same as
      
      >>> s = 'The value of x is ' + str(x) + ', and y is ' + str(y)
      

      You can also build strings with standard C-style format strings:

      
      >>> x = math.pi
      >>> a = '%f %f %f' % (x, x*x, x*x*x)
      >>> print a
      3.141593 9.869604 31.006277
      
    2. Some common commands for dealing with file objects:

      • open() returns a file object, and is most commonly used with two arguments: "open(filename, mode)", where 'mode' can be:
        • 'r' (read)
        • 'w' (write)
        • 'a' (append)
        
        >>> f=open('/tmp/workfile', 'w')
        
      • f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned
        
        >>> f.read()
        'This is the entire file.\n'
        
      • f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string
        
        >>> f.readline()
        'This is the first line of the file.\n'
        
      • f.readlines() reads all the lines from the file and stores them in a list of string (each line being an item).

      • f.write(string) writes the contents of string to the file, returning None.
        
        >>> f.write('This is a test\n')
         
        
        
      • f.close() is used to... close the file.

    2.12 Some relevant modules...

    ... that you may need for this and coming assignments. Don't forget to check them up.