Python 1: Introduction to Python


1.1 What is Python ?

And now for something completely different ...

The computing language known as Python was named after the famous and hilarious TV comedy series called "Monty Python's Flying Circus", not after the beautiful and charming non-venomous reptile.

1.2 Python books and Internet resources

Recommended books

The O'Reilly books (Learning Python and Programming Python) are recommended for second-year Python based undergraduate and HND modules. However, in situations where a student considers that the pre-requisite programming knowledge assumed for III and IV numbered taught modules (i.e. having knowledge of and the ability to apply at least one programming language) not to be secured, the following book might be considered by students intending to remedy the deficit:

Title: Learn to Program Using Python  Author: Alan Gauld   Publisher: Addison-Wesley, 2001, 288 pages. 

Python is not yet (January 2002) taught for any first-year programming modules. If and when it is, Alan Gauld's book is likely to be adopted.

Title: Learning Python   Authors: Mark Lutz & David Ascher  Publisher: O'Reilly   Description: A good guide to Python as a programming language, likely to be used by a student who already knows how to program using another language.

Title: Programming Python   Author: Mark Lutz   Publisher: O'Reilly   Description: An extensive guide to creating powerful applications using the Python language, including web CGI applications, other Internet interfaced programs and applications involving GUIs. This book assumes the reader already knows Python basics.

Internet Resources

Title: The Python Tutorial  Author: Guido van Rossum  URL:  Description: An on-line tutorial guide to the Python language. Students of Python are likely to consider the time learning this one well spent.

Title: The Python Documentation Index   Author: various authors   URL:  Description: An extensive resource index which accesses the above tutorial, the Python language reference, an extensive Python library reference and other on-line resources. The main documentation referred to in this index can be downloaded as a single bundle. Serious Python programmers are likely to need to make frequent and extensive use of this significant and free resource.

Title: Python Downloads   URL:  Description: Freely downloadable and easily installable versions of Python for platforms including Linux, Windows and Solaris. Active Python downloads include integrated development environment support. This site also provides access to the more advanced Komodo integrated development environment.

1.3 Python as a programming language

Python is Interpreted

You don't have to edit, save and compile your code every time just to run a simple program containing a few lines of code. You can of course save your code in a file in order to run your Python program (or "script") as often as you want without having to rewrite it. But you don't have to do this just to try out a Python expression directly in the interpreter. As with some other "scripting" languages 10 lines of Python code can do a lot more useful work than would be achieved with 50 source code lines of a compiled systems-programming language such as 'C' or Java. The disadvantage is that the Python code is likely to require more memory and CPU time to operate.

In the following example, the Python interpreter is used interactively in "command-line" mode, and the program output is displayed directly:

>>> import math
>>> radius=3
>>> area=math.pi*radius*radius
>>> print area

Python is Object Oriented

The advantages of code reuse (meaning you don't have to redo programs that others have already written) and object orientation are built into Python programming from the ground up, rather than tacked on at a later stage as with some other languages (e.g. C, Pascal and Perl). You'll find plenty of explanations of what this all means in books devoted to the subject, but for now I'll just mention that human beings naturally tend to use OO (Object Oriented) concepts such as classifications (classes), e.g shrubs , and things (objects) which we classify in this way (e.g. the red rosebush in my front garden). We also tend to classify classes into hierarchies of such, e.g. grasses, shrubs and trees are kinds of plant, which along with animals are kinds of living organism.

Computer programming languages which allow for classes and instances (or objects for example the general set of dwellings is a "class" and the specific instance of this class, my house) tend to match the way we think about things more closely than languages which restrict our thought in mechanical terms of variables, values and functions. This allows us to create and understand more interesting and complex programs and for programmers to encapsulate logic as classes which are more flexibly reusable by other programmers.

Python has a simple syntax and is easy to learn

A growing number of students are learning Python as a first programming language. The meaning of Python code is relatively intuitive, without needing as many additional comments as other languages would. Python forces programmers to get into the habit of laying out programs correctly, as the control of flow is directly determined by the indentation. You are more likely to understand your own Python programs when you need to maintain them in 6 months' time than your are with programs written using some other languages.

Python is free software and is portable

You have access to the source code for Python itself and can change and extend it, and are free to copy, buy and sell it. It runs on most modern operating platforms, such as Linux, Palm, Macintosh, Solaris, different versions of Windows and BeOS. It is easy to create Python programs which run identically on many platforms, including programs with complex GUIs.

Python is powerful enough to be used for large and complex programs

Python is used for GUI applications of some complexity, e.g. the Linux Kernel configuration system. It is used as a glue language, e.g. for interfacing business databases to web sites and for systems administration applications in a multi-user networked environment. It is used for text processing, e.g. to process, validate and respond intelligently to the input submitted in web forms using the web CGI interface.

1.4 Simple Python program examples

The way a program is coded in Python tends to reflect the way we think about solving a problem.

The first example asks the user for a temperature and prints:  "too hot" if temperature > 80,   "too cold" if temperature is < 60   and just right otherwise   (if otherwise, 60 <= temperature <= 80) .  
temp=input("enter temperature: ")
if temp > 80:
    print "too hot"
elif temp < 60: # elif is short for else if
    print "too cold"
    print "just right"

This Python program file must be indented consistently for the if, elif and else statements to work.

Here is what this Python program does when we run it 3 times with temperatures in the 3 ranges detected:

[rich@copsewood python]$ python
enter temperature: 59
too cold
[rich@copsewood python]$ python
enter temperature: 65
just right
[rich@copsewood python]$ python
enter temperature: 89
too hot
[rich@copsewood python]$

Our second example involves solving a minor problem.

When asked how we would define a prime number, we could say that this is a whole number greater than or equal to 2, which is not exactly divisible by any number except for 1 and itself.

Considering this definition further, to work out whether a number is exactly divisible we could look for any remainder of zero when dividing this number by all other numbers (let's say "values" to avoid confusion) in the range between 2 and the number minus 1.

If we find a remainder of zero then we know the number isn't prime.

If we check the values in the above range without finding a remainder of zero then the number is prime.

A Python program which uses this definition and approach (algorithm) to report whether a particular number input by the user is prime or not looks similar to our definition of a prime number:

# Python prime number testing program
number=input("enter a number greater than 2: ") # ask user to enter a number
for value in range(2,number-1): # check for factors between 2 and number-1
    # check if remainder when dividing number by value is 0
    if number % value == 0: # value is a factor of number if this is true
        print number, "is not prime"
        exit # quit program now
print number, "is prime" # this must be true if we havn't quit the program yet

The lines or parts of lines in the above program after '#' characters are not part of the program, these are comments, or explanations of the code within the program that does the work.

This is what happens when we run the above program and input prime and non prime numbers:

$ python
enter a number >= 2: 97
97 is prime
$ python
enter a number: 49
49 is not prime

Python is powerful enough to be used for large and complex programs

Python is used for GUI applications of some complexity, e.g. the Linux Kernel configuration system. It is used as a glue language, e.g. for interfacing business databases to web sites and for systems administration applications in a multi-user networked environment. It is used for text processing, e.g. to process, validate and respond intelligently to the input submitted in web forms using the web CGI interface.

1.5 Creating and running a Python program

Using the interpreter Python command line

Simple programs can sometimes be tested using the python interpreter directly. You typically run the Python interpreter either from a start menu, or by clicking an icon on the desktop or through a file explorer or by running the command line or shell program provided by your operating system (MS-DOS on Windows or Bash on Linux/Unix) and entering the command:


You will then see information about the version of Python, when it was built and the operating system for which it was built followed by the Python prompt: >>> e.g:

Python 2.0 (#1, Apr 11 2001, 19:18:08)
[GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux-i386
Type "copyright", "credits" or "license" for more information.

In the following example, the Python interpreter is used interactively in "command-line" mode. The program is typed as a number of lines each line directly after the >>> Python prompt. (You don't type the >>> characters, Python does.) You start a new line by pressing the <enter> key and the program output is displayed directly:

>>> import math
>>> radius=3
>>> area=math.pi*radius**2
>>> print area

Using the interactive prompt you could have entered just 'area' to print its value instead of 'print area'.

If your typing or spelling skills are such that you can't get the above example working easily because you keep typing things wrong or it takes you so long to find each letter that the whole excercise takes you more than a few minutes to get right, you could confirm the operation of Python more simply by trying:

>>> print "hello"

instead, in which case the system should respond with:


You might also try saving yourself a little time by using shorter names, e.g: calling radius r , and area a instead:

>>> import math
>>> r=3
>>> a=math.pi*r*r
>>> print a

All computer languages have areas of flexibility (e.g. in choice of variable names: a and r demonstrated above so long as you use the same name every time for the same variable) and things you have to get exactly right. For example you have to spell words such as "import" and "print" correctly. In Python as in most other programming languages variables and keywords are case sensitive, i.e. variables called a and A are references to different objects.

(Hint: For how many years into the future are you likely to be using a computer keyboard ? If your answer is more than 1 or 2, then the time you spend learning how to touch type in the next 2 months or so will be repaid very many times over. To do this you can download and install free programs that will teach you this skill if you spend half an hour a day for 5 days a week for the next month or two. Not having to think about what your hands are doing, because they touch type automatically, will also help you to think more about your program code, or the messages or reports you are writing.)

Running a Python program saved as a file

The above approach is all well and good for experiments and tests (of which you will have to carry out very many to become a competent programmer), but you won't want to retype a program with other uses every time you run it, once you have got it to work. For this purpose you will need to save the source code in a file.

Using a text editor (e.g. emacs, vi, notepad, or one provided by the Python integrated development environment or IDE) create a file with the following 4 lines of text:

import math
print area

and save it as a file called (If you are using Windows and Notepad you might need to enclose the filename in double quotes "" to prevent the system incorrectly and unhelpfully naming it ).

On a system with a shell prompt (MS-DOS, Unix or Linux) you can then run your program using the command:


and should see the displayed output.

If this doesn't work first time try to compare what you actually typed with the program above. The error messages given by the interpreter should indicate approximately where the error occurred, e.g. through a line number. Having repeatedly to edit a file, save it and carry out test runs and observe the code and outputs carefully is a cycle you will have to get used to as a programmer in order to:

Programming is made more difficult on systems with neither command line shells nor a Python IDE (integrated development environment). In this situation you may be able to double click on the icon for your file using a file explorer. This will run your python program if it is saved with an extension .py or (e.g. on Apple Macs) other means of associating the file with the Python interpreter.

However, If you system has Python then you should also be able to use this in Python command line mode. Running the Python interpreter will enable you to run saved Python source files by importing them.

E.g. having created and saved the above file :
>>> import circle

Here, the import python command will look for a file with the name you import followed by .py ( or .pyc in some cases) and run it as a program To run the same program again, import doesn't work, you have to use reload instead.

If you are using a Python IDE, having saved your file you can run it by using a "Run" button or menu option within the IDE GUI.

Pausing your program before it exits

If clicking a file icon runs the program file in a console which vanishes when the program exits before you have a chance to see the output you can make your program pause by forcing it to wait for keyboard input. To do this, edit your program and add the extra line of code at the end, then save and run:

import math
print area
raw_input("press enter")

A shortcut for Unix/Linux Python users

If you are using command line operation to edit,test and debug your Python programs, and you indicate to the kernel that your program is to be run by the Python interpreter, your program can then be run as if it were any other Unix command.

To do this first find out where the python interpreter is located using the command:  which python

The result of this path search should be a pathname typically:   /usr/bin/python

If you then put this interpreter pathname after the #! characters on the first line of your program e.g:

#!/usr/bin/python  print "hello Python/Unix world\n" 

save this as pyunix and use the command:  chmod +x pyunix

to make it executable, you can then install the program in a directory on the system (e.g. in /usr/local/bin ) where your path environment variable finds commands and run it using the command:  pyunix

Or run it from the current working directory as a command:  ./pyunix

instead of having to say:  python pyunix

If you use this approach, the first line has no effect if you run your program by other means, as Python just treats it as a descriptive comment. Also, if the kernel knows which interpreter to use from the file contents there is no reason (other than for human directory/folder reading purposes) to indicate the type of the file through a .py filename extension, as you may want to give your custom commands created using python programs shorter names.

1.6 Some number operations

Operator        Operation
+		Add
-		Subtract
*		Multiply
/		Divide
%		Remainder (or modulus)
**		Exponentiate (or raise left operand to power specified by right)
=		Assign

E.G: a=b+c

Takes the result obtained by adding the numbers referred to by b and c and makes a refer to this result.

If you combine operations, exponentiation is first, then multiplication, division and modulus happen before addition and subtraction. E.G: 8+3*2 evaluates to 14, not 22. You can force the order of operations using () brackets, e.g. (8+3)*2 evaluates to 22.

Be aware that the result of 7/2, currently 3, will change for Python versions 3.0 onwards, when 7/2 becomes the same as 7/2.0, which is 3.5 . Python 2.2 introduces the // operator which gives floor division (rounding down) for those who want to write code which depends upon the loss of the fraction when dividing one integer by another.

In general the = assignment causes the result of the expression on the right to be referred to by the the name on the left. There are some additional assignment operators:

+=    -=    *=    /=    %=

where in general a op= b is the same as a = a op b , and "op" is one of the operators: +,-,*,/,%   e.g. a+=2 is the same as a = a+2

You might read this as "add 2 to the current value of a ".

1.7 Some string operations


Strings can be assigned to names and joined together using the + operator. In string context this kind of addition is sometimes called "concatenation". E.G:

>>> a="Fred"
>>> b="Bloggs"
>>> print a+b
>>> print a+" "+b
Fred Bloggs


Strings can be quoted using "double"quotes or 'single'. This allows you more easily to embed quotes within strings. e.g.

a='Joe said "hello" to mary'
b="Harry's game"

If you want to define strings containing newlines and arbitrary white space you can triple quote them e.g:

	<title>trivial html example</title>
	<body>Hello HTML world!</body>

Escape characters

\n and \t can be used to embed newlines and tabs e.g:  print "hello world\ngreetings again"  prints a newline between world and greetings. The print command gives you a single newline at the end of the output string by default. You can have 2 if you want, e.g. print "hello world\n"

To turn the default trailing newline off you can use a trailing comma after the quoted string. E.G. the program file:

print "no newline",
print "before next print"

Outputs: no newline before next print

Python inserts a space in place of commas used to print multiple objects e.g:

>>> a=5
>>> b=3
>>> print a,b
5 3

To print out a literal backslash (\) you will need 2:  >>> print "c:\\autoexec.bat"  c:\autoexec.bat  

Interpolation of values within strings

Sometimes you will want to print out a number inside a string, or to substitute variable parts of a string

import math
>>> print "PI is: %f" % math.pi
PI is: 3.141593

You can change the precision to N decimal places using %.Nf e.g:

>>> print "PI to 3 decimal places is: %.3f" % math.pi
PI to 3 decimal places is: 3.142

You can print integers using %d . If you give Python the wrong conversion letter, unlike 'C' it will try to do a sensible conversion before printing e.g:

>>> print "%f" % 123
>>> print "%d" % math.pi

You can interpolate a string within a string using %s, and interpolate multiple values within a string by specifying these as a "tuple" which in Python is a round bracketed, comma separated list.

>>> name="Fred"
>>> age=42
>>> height=1.95
>>> print "%s is %d years old and %.2f metres tall" % (name,age,height)
Fred is 42 years old and 1.95 metres tall

The values in the tuple are interpolated in the string in left to right order.

To get a literal % within an interpolated string use %% e.g: 

>>> print "the current VAT rate of %.1f%% is not applied to books" % 17.5
the current VAT rate of 17.5% is not applied to books

If there is no value to interpolate a single % is printed directly.  

>>> print "50%"