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:
- Dynamic Typing - Python works out all of your types for you, there's no need for compicated type declarations.
- Built in Object Types - Commonly used structures such as lists, dictionaries and strings are built in.
- Library Utilities - Including routines for networking, compression, multimedia, threading, regular expression and more, all included as standard.
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:- strings - "Lumberjack" or 'Barber' (single or double quotes are allowed).
- lists - [0,1,2] or [] or [0,[1,2]] or [0,"foo",5j] (not all items need be the same type).
- tuples - (0,1,2) or () or 0,1,2 (brackets are only necessary for empty tuples or when precedence rules demand it. Again, not all items need be the same type)
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+string2 | Concatenate two strings. |
| string*n | Repeat the string n times |
| for x in list | Iterate through a sequence (more on this later) |
| x in tuple | Check 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]=n | Assign 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:
| Statement | Role | Example |
| a = b | Assignment | rod, jane, freddy = 40,50,60 |
| foo() | Function call | stdout.write("Hello world!") |
| print string | Outputting objects | print "Hello!", world |
| if test: action1 elif test: action2 else: action3 | Conditionals | if x == 20: print "It's twenty!" |
| for x in list: loop-body | Iteration | for n in [0,1,2,3,4,5]: print n |
| while cond: loop-body | Loops | while x < 10: x = x + 1 |
| pass | Placeholder | while 0: pass |
| break | Exit loop | while 1: if x <= 4: break |
| try: test except exception: failure | Exception catching | try: action() except: print "Broken!" |
| raise exception | Trigger exception | raise IOError, EOFError |
| def fn(args): body | Defining functions | def multiply(a,b): print a*b |
| return value | Return from a function | def multiply(a,b): return a*b |
| class name(parent): body | Declaring object types | class 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:
- handle = open(filename,"r") - open a file for reading.
- handle = open(filename,"w") - open a file for writing.
- handle.write("Hello") - write a string to a file.
- handle.writelines("Hello","Goodbye") - write lots of strings to a file.
- string = handle.readline() - read a line from a file (including the trailing newline character).
- handle.close() - close the file.
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:
- pickle.dump(variable,handle) - write the variable to the file.
- variable=pickle.load(handle) - read the variable back from the file.
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:
- matchobj = re.match(pattern,string[,flags]) - This function returns a MatchObject object if successful, or None if it fails. flags can be re.IGNORECASE, re.VERBOSE (which allows comments inside the pattern, re.MULTILINE or a number of others.
- newstr = re.sub(pattern,replacement,string[,count=0]) - Replace pattern in string with the given replacement. count is the maximum number of replacements, with 0 (the default) meaning replace all occurrences.
- matchobj.group(n) - return the nth subexpression in the match object - similar to perl's built in variables $1, $2, etc.
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:
- Fancy output formatting
- Classes
- Exception handling
- Keyword arguments
- Extending and embedding
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.
- Write a program to reverse the order of lines in a file.
- Store the contents of a web page in a variable.
- 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 - Use the rfc822 module to work out who an email is from.
- Write a fractions class, including at least functions for addition, subtraction, multiplication and division and an output function.
- 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.
