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.
The official Python language website is www.python.org.
The following Python tutorials are available on the web:
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/
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.
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
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
xemacs:Editing a file ending in .py will invoke the Python
mode. A couple of useful commands in this mode are:
.py
buffer) executes the current buffer in the Python interpreter
process.
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()
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"
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
Python has the following built-in data types:
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.
>>> 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
>>> 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)]
>>> atuple = ('There', 0.34)
>>> btuple = ('bigram', [('There', 'is'), 0.34])
How can we manipulate sequence types:
Sequence types are indexed as arrays:
>>> a
'There is no "place" like home'
>>> a[0]
'T'
>>> a[1]
'h'
>>> alist
['There', 'is', 'no', 'place', 'like', 'home']
>>> alist[0]
'There'
>>> btuple
('bigram', [('There', 'is'), 3])
>>> btuple[1]
[('There', 'is'), 3]
>>> btuple[1][0]
('There', 'is')
You can obtain slices of a given sequence with the slicing operator
":". The second argument is non-inclusive,
i.e. alist[m:n] gets you the portion of the list
containing all elements beginning with position m and
ending with position n-1. Either argument can be
omitted.
>>> alist
['There', 'is', 'no', 'place', 'like', 'home']
>>> alist[0:3]
['There', 'is', 'no']
>>> alist[:3]
['There', 'is', 'no']
>>> alist[2:]
['no', 'place', 'like', 'home']
>>> a
'There is no "place" like home'
>>> a[:4]
'Ther'
Slices of any sequence type can be concatenated using "+":
>>> 'there is no place' + ' like home'
'there is no place like home'
>>> (1, 2) + (3, 4)
(1, 2, 3, 4)
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
Remember that only lists are mutable. That means that you can modify any element of the list and also modify slices of lists:
>>> alist = [1, 2, 3, 4, 5]
>>> alist[0] = 'a'
>>> alist[1:3] = ['b', 'c']
>>> alist
['a', 'b', 'c', 4, 5]
Also, the List data type has methods such as append(x),
insert(i, x), index(x), sort(), etc.
>>> a = ['There', 'is', 'no', 'place', 'like', 'home']
>>> a.sort()
>>> a
['There', 'home', 'is', 'like', 'no', 'place']
Those and other list-related operations will most probably be needed when processing text. Check the Python tutorial for a complete view on that here.
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.
The following values are false in Python:
None
All other values are true.
Boolean operations: not, and, or
>>> a = ''
>>> b = 32
>>> a or b
32
>>> a or not b
0
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
All the standard loop and conditional constructs are present:
if:
if a != 0:
print b/float(a)
else:
print "Attempted division by 0!"
while:
while (a % 2 == 0):
a = a/2
for:
A Perl loop that iterates over the elements of an array
foreach $elem (@myarray)
<do the loop commands>
myarray = [e1, e2, e3]
for e in myarray:
<do the loop commands>
In Python, one customarily uses range() function
for the loop variable in for loop.
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
A standard C/Java/Perl style loop
for(i = 0; i < n; i++) {
<do the loop commands>
}
for i in range(n):
<do the loop commands>
continue, break, else:
These are used just like in C.
The continue statement
continues with the next iteration of the loop.
The else clause on loops is executed
only if the loop was not exited through break:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
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
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()
>>> 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
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:
>>> 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.