login

Home - Tutorials & Guides - Introduction to Python

1.Introduction

Never mind the buzzwords.

Why would anyone want to learn python, when another scripting language such as Perl would appear to do the same job? Python is an object oriented scripting language. It's easy to learn, easy to use and extend and is a useful tool for rapid prototyping. It also features a GUI programming toolkit (Tk) which can be used to create graphical front ends very quickly.

This document assumes knowledge of programming in general, although you can safely ignore the OO bits if you prefer. There will be a summary of pythons main features, a summary of the syntax and built in types, and some of the more useful and important built in modules.

Object Oriented

Python supports object oriented programming (OOP) concepts such as polymorphism, operator overloading, multiple inheritance. Furthermore, it's possible to derive python classes from base classes implemented in C++ and Java.

If, however, you don't understand or like OOP, it is merely an option in python, so you can ignore it if you wish. You will find, however, that python makes OO concepts much easier to learn than certain other languages!

Free

Python is freeware (or Open Source, more accurately). There are no restrictions on using it in your own programs (perhaps as a scripting language, which, incidentally, is remarkably easy to do although we won't be covering it here).

Python also has a very active online community, due to the nature of the beast that is Open Source software. You'll always find help (and flame wars) in comp.lang.python.

Portable

Python runs on virtually every major platform in use today. And MS DOS. Python programs are compiled into a bytecode, which will behave the same on any platform with a compatible version of python installed.

The GUI system which comes with python (Tkinter) is portable to X Windows, MS Windows and the Macintosh (ie every major GUI platform).

Powerful

Python has a number of features which are not often found in scripting languages such as Tcl and Perl, making it more suitable for larger projects. Some of these features are:

There are a number of other features for helping develop large programs such as modules, exception handling, and of course objects.

Extensible/Embeddable

Python can easily be extended, or embedded in other languages. In this way, it is possible to write a C or C++ back end for a program which does all the heavy computation, with a front end written in Python/Tk (which is far quicker to write and debug than C!). Also, by embedding python code in a C program, it can be used as an extension or scripting language for that program.

RAD!

Python is both groovy, and good for Rapid Application Development. To python, components written in Python and C (or indeed any language) look the same. For this reason, it is possible to write an initial prototype in python (this is much easier - I may have mentioned) and fill out any details in another language later.

2.Built in types

Before we cover syntax, let's have a look at the basic types which a python program can use. These fall into three major categories - numbers, sequences and dictionaries (okay, so there's only one dictionary type...)

2.1 Numbers

As well as the usual integer and floating point numbers, python supports a complex number type. These are written as a+bj. Other than that, there is nothing more interesting about numerical types in python than in any other language...

2.2 Sequences

The three sequence types in python are tuples, strings and lists. These share a number of characteristics, so we'll lump them together here, and explain the differences in a moment. The constant form of each of these types is written as follows:

Sequence operators and functions

The following table summarizes the operators and functions which are common to all sequence types:

list[i]Indexing - get the ith element of list (beginning at 0).
list[i:j]Slicing - get elements between (and including) the ith and the jth.
len(list)Get the length of the sequence.
string1+string2Concatenate two strings.
string*nRepeat the string n times
for x in listIterate through a sequence (more on this later)
x in tupleCheck for membership of a tuple

Immutable and Mutable

The difference between the sequence types is that some are mutable and some are immutable. This means that in certain types (mutable types), items can be changed in place (ie the sequence can be modified), and in others, items cannot be changed. Strings and tuples are immutable, and lists are mutable. This, of course, means that there are some extra functions you can apply to lists...

List operators and functions

The following functions are available to list objects:

list.sort()Sort the items in a list in ascending order
list.reverse()Reverse the items in a list
del list[i]Remove an item from a list
list[i:j]=[]Remove a slice from a list
list[i]=nAssign to an index
list[i:j]=[x,y,z]Assign to a slice

2.3 Dictionaries

A dictionary is similar to a list, with the exception that items are stored and retrieved by a key, rather than an index offset. Like lists, they are mutable, but unlike lists, the contents are not ordered (well, actually they are, but only for fastest possible lookup - to the user they appear unordered).

A dictionary constant is written as dict = {'spam':42, 'ham':18, 'jam':6}.

To lookup the values in the previous example, we can ask for dict['spam'], dict['ham'] or whatever. This is similar to perl's associative array (or hash) or a hash table in a lower level language like C (which, of course, you'd have to implement by hand).

Note that the key does not need to be a string. In fact, it can be any immutable object - tuples, for example, can be used to allow compound key objects. Classes can also be used as keys, provided they have the appropriate protocol methods.

Some common dictionary operators and functions are:

dict['foobar']Indexing by key
dict['foo']['bar']Multidimensional indexing
dict.has_key('thurlingdrome')Test for a key being in the dictionary
dict.keys()Return a list of possible keys
dict.values()Return a list of all values
len(dict)Return the length of a dictionary
del dict['moose']Remove an item from a dictionary

3.Syntax

Python has a very small and clean syntax - most of the real functionality is in the library which comes as a standard part of the distribution. This section deals with the basic syntax.

Important note - indentation!

Unlike most other languages, indentation matters in python. Lexical scope is determined by how far a line is indented. For example:

if x < 0:
   print "Hello!\n"
   print "Bye!\n"
print "Foo!\n"

"Hello!" and "Bye!" will only be printed if x<0, but "Foo!" will be printed anyway. A new level of scope is started by the colon at the end of the first line. Note also that because of this, python does not require a semicolon at the end of the line (like many other languages). However, it won't complain if you use it as semicolons can be used to separate statements on the same line.

Python's syntax is small and clean and should be easily picked up by anyone familiar with another programming language. It can be (mostly) summed up by the following table:

StatementRoleExample
a = bAssignmentrod, jane, freddy = 40,50,60
foo()Function callstdout.write("Hello world!")
print stringOutputting objectsprint "Hello!", world
if test: action1
elif test: action2
else: action3
Conditionalsif x == 20: print "It's twenty!"
for x in list: loop-bodyIterationfor n in [0,1,2,3,4,5]: print n
while cond: loop-bodyLoopswhile x < 10: x = x + 1
passPlaceholderwhile 0: pass
breakExit loopwhile 1: if x <= 4: break
try: test
except exception: failure
Exception catchingtry: action()
except: print "Broken!"
raise exceptionTrigger exceptionraise IOError, EOFError
def fn(args): bodyDefining functionsdef multiply(a,b): print a*b
return valueReturn from a functiondef multiply(a,b): return a*b
class name(parent): bodyDeclaring object typesclass Foo(Bar): data=[]

4.Library classes and modules

Most of the power of python lies in its extensive module and class library. The following subsections show how to use some of the more important or interesting ones. This section is rather brief - for full details on these modules, you should consult the python library reference (available here).

Before a library module can be used, it must be imported using the 'import' statement. For example, to import the functions in the re library, you must put "import re" at the top of your program. Functions in this module can then be called using the syntax re.functionname().

An alternative form is "from re import *" which has the same effect, but there is no longer any need to prefix function calls with re.

4.1 Files

A programming language is fairly useless unless we can store and retrieve data with it - so here's how to do it with python. There is a built in file object which can be used to read and write text files. A file object is created using the open function, and has methods called write, readline, read, writelines and close (among others) which are used as follows:

Note that files are built in, so no import statement is required.

4.2 pickle

The disadvantage of the file class is that only strings can be read or written. To read any other data type (including numbers) requires a certain amount of fiddling. The pickle module, however, makes this very easy. To read or write data from a file, first open it for reading or writing as above. Then the pickle module's functions can be used, as follows:

Types which can be pickled are any number types, strings, tuples, lists and dictionaries. User defined classes can be pickled given the appropriate methods.

4.3 re

Of course, a scripting language needs to cope with regular expressions. This is where the re module comes in. This module includes functions for matching subexpressions, search and replace, and all the usual regular expression stuff. Some of the functions available to you are:

4.4 Tkinter

Tkinter is python's interface to the Tk GUI library. This is a large topic in itself, and this section is merely to inform you of its existence. The following piece of code will create a window with a button in it:

 from Tkinter import * class PressButton(Button): def
__init__(self,master): Button.__init__(self,master, text="Do not press this
button", command=self.again) def again(self): self.configure(text="Do not
press this button again") root = Tk() w = PressButton(root) w.pack()
root.mainloop() 

5.Where to now?

There's quite a few things we haven't covered in this document which you may be interested in or find useful. All of it is covered in the python language reference and tutorial - good things to look at would be:

6.Exercises

For these exercises, it will be very useful to have the python library reference to hand. This can be found http://compsoc.dur.ac.uk/doc/python/html/lib/lib.html.

  1. Write a program to reverse the order of lines in a file.
  2. Store the contents of a web page in a variable.
  3. Write a program to display Pascal's Triangle. ie the output should look like:
    1
    1 1
    1 2 1
    1 3 3 1
    ...etc
  4. Use the rfc822 module to work out who an email is from.
  5. Write a fractions class, including at least functions for addition, subtraction, multiplication and division and an output function.
  6. Implement a full featured word processor with a graphical interface.

To create a python program, you need to create a text file where the first line is:

#!/usr/local/bin/python

and when you've finished and returned to the command line, type:

chmod u+x filename

to make the text file executable. Now, just type filename at the command line, and your program should run. It is suggested that you add the .py extension to your python programs so that you know they're written using python.

7.References

http://www.python.org/ - all things python.
http://starship.skyport.net/ - all things python, less formally.
http://www.python.org/doc/FAQ.html/ - python FAQ.

Last edit: Wed 13th Aug, 01:39 p.m.

Google

External Links

Compsoc Wiki
Compsoc Library
DSU

Upcoming Events

There are no upcoming events planned. Check the CompSoc Wiki in case of emergency

RSS | iCal

Sponsors

ARM
DNUK
O'Reilly
No Starch Press
Durham Students Union

Random Poll

This statement is False


View results
Submit a new poll
All polls

This section exists to trap prefetching clients. Please just ignore it if you have css disabled and thus can see this. Do not click this link unless you want us to think you are a bot