Department of Engineering


Python Tutorial



This document makes no attempt to exhaustively cover the Python computing language. It introduces just enough Python for you to write small programs and run them. The idea is to give you the confidence to learn more yourself - like learning to snowplough as the first stage when skiing, or learning not to be scared of the water when learning to swim. Once you can run little programs that you've written, you can copy example source code and experiment with it to learn how it works. Like skiing and swimming, you can only learn programming by doing it.

Towards the end it introduces aspects of Python that you could do without when writing simple code, but they make your programs shorter and easier to read. These extra techniques are useful when writing longer programs.

The Python language is a scripting language (it doesn't have to be "compiled") and it's freely available on many types of machines. Among the users of Python are YouTube and Google. Add-ons like NumPy, Scipy and Matplotlib allow Python to be used effectively in scientific computing.

The document includes some sections of extra information that you can show or hide. If you want to see all the extra sections, click on this Extras button. Use Ctrl + and Ctrl - to adjust the text size.

Start sessions on the CUED central system by clicking on the greenarrow icon at the bottom of the screen and then clicking on the All CUED Applications/all other start scripts/Start Python option. This will put some icons on the screen for you, and start a program called idle, which makes it easier to write programs in Python

If you want to work from home and use Linux or Macs you may not need to install anything extra. If you use Windows, see Southampton University's Download and install Python software page. You won't need the extra packages they mention.

Why Python?    [ back to contents]

It's a good question. You're likely to use several programming languages in your career because no language will cope with all situations. Here are a few reasons why Python might be useful to you

  • It's free - Mac and Linux machines have it pre-installed. It's easy to install on Windows
  • It's easy to use - Engineers aren't computer scientists. They want answers, and Python has a gentle learning curve (compared to Java and C++ anyway)
  • It's expandable - There are add-ons for engineering and maths topics. There are also add-ons to make it faster so that big engineering tasks can be performed. If you want to turbo-charge part of your program you can write your own add-on in Fortran or C++
  • It's adaptable - It's a "glue language" to connect things up. Engineers use many different programs. From Python you can run a number-crunching program, get some information from a web page, do a few calculations then produce an Excel file - all in a few lines of code
  • It's modern - Engineers have made major contributions to maths and computing. Python has all the advanced features that cutting edge programmers and mathematicians desire.
  • The University likes it - There's local support from the computing service - courses in Scientific Computing, etc.

This document uses Python 3. Its print is a function rather than a statement, so if you want to use Python 2 with this document you'll need to replace print ("hello") by print "hello", etc.

Variables    [ back to contents]

You can use Python like a programmable calculator - interactively from the command line. If at your prompt in idle you type


and press the Enter key you'll get 4, but you can also do


and get the answer 4. The x used here is a variable - a place to store something, and you use a = sign to put something into a variable. You can also store text in a variable - e.g.


but if you then try


you'll get an error message because you can't add a number to text. You can however do

x+" and pears"

because variables of the same type can usually be added together.

You can set variables to the value of other variables. For example, you can do


which will give y the value 3. Similarly you can do


The second line might look a little strange ("how can x ever be equal to x+1?") until you remember what the equals sign means in this context. x will end up with the value 3.

Python is fussy about variable names - they can't have spaces or dots in them, nor can they begin with a digit. They shouldn't clash with the name of something that already exists. Python has lots of built-in functions (max for example). Typing max=100 is legal, but it stops you easily using the max function subsequently. So don't use names that are too general

Note also that Python distinguishes between upper and lower case characters - num and Num are different variables.

[show extra information]

Types of Variables    [ back to contents]

As we've seen earlier, variables like x can "contain" different types of things - integers, characters, etc. Doing x=999 is different from doing x="999", though if you did print x after both of these commands, you wouldn't notice a difference. But you would notice a difference if you tried print x+1. If you try to add a number to text you'll get an error message like the following

Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'int' objects

so it's important to know about a variable's type. To find out what type of thing is in a variable, use the type command - e.g.


tells you that x is an integer. You can convert values from one type to another using commands called int, str (to convert to text), float (to convert to a floating point number), etc. For example, the following works

print(int(x) +1)

One type of variable you haven't met yet is bool. A variable of this type can be either True or False.

Strings and Characters    [ back to contents]

Strings are sequences of characters. If you add 2 strings using +, the 2nd string is appended to the 1st. If you want to find the length of a string you can use a function called len(). Here's an example of appending to, then finding the length of, a string. Try to guess what it will do if you run it, then copy/paste it into the idle window (note that Python is fussy about indentation. If pasting causes spaces at the front of any of these lines you'll get a "IndentationError: unexpected indent" message. Later you'll see how use indentation advantageously)

s=s+" world"

To find a particular character of this string (the 3rd, for example) you can do this


Note that the numbering of the characters starts at 0. You can also pick out a range of characters. Try


Note that this picks out items s[2], s[3], and s[4] but not s[5]

You can use single quotes or double quotes around strings.

[show extra information]

Lists and Tuples    [ back to contents]

When you have a program with lots of variables, giving each a different but useful name can be tricky - it's like having a street where the houses have names rather than numbers. Very soon you'll want to collect variables that are related into some kind of tidy group. Python has various ways of doing this. We'll start by looking at lists because these are used in nearly every Python program. Here's a shopping list of 3 items.

shopping=["apples", "bananas", "carrots"]

You can discover the list's length and pick out particular items in the same way as you did with strings. len(shopping) will tell you how many items are in the list. The 2nd item can be accessed using shopping[1] (numbering begins at 0). To find the length of that item you could use len(shopping[1])

You can replace items in a list. You can have a mix of types of things in a list too, so


is possible. You can append and delete items too. After

del shopping[0]

you should be left with a shopping list containing 3 items - 999, carrots and dates. You can have lists of lists, so

megashop=[7, shopping, "nine"]

is possible. This is a list of 3 items whose 2nd item is another list. To find the length of the 3rd item in the list that's the 2nd item of megashop you can do


Lists of numbers are common, so there's a function called range to create them easily


creates a [1, 2, 3, 4] list and


creates [1, 3, 5] (the list runs from 1 to 5 in steps of 2).

You can create lists by duplicating existing ones. For example, if you type [1, 2]*5 you create a new list which is 5 copies of the original one. You can use this technique to create a list full of a particular number. E.g. [0]*8 creates a list of 8 zeroes.

Tuples are like lists except that you can't change them. To create them you use ( ... ) instead of [ ... ]

Loops    [ back to contents]

For repetitive tasks, use loops. Here's a for loop

for number in [1, 2, 3]:

Make sure you don't forgot the ":" symbol. When you type this in you might notice a few things. You've probably already noticed that idle colour-codes your program - function names are purple, keywords are orange, etc. When you hit Return after the colon, some spaces are added on the next line. These spaces matter! The for statement is going to make some lines run several times. These lines are call the body of the loop. The indentation is a way to show how many of the subsequent lines need to be repeated. When you hit Return after the "print number" line, the cursor will be indented on the next line, giving you a chance to continue the body of the loop (the lines all have to be indented by the same amount). If you press Return again, idle will know that the loop has finished and you should get the output. number is set to 1 and print number is run. Then number is set to 2 and print number is run. Finally number is set to 3 and the print(number) line run.

The range function goes well with the for statement. Try the following

for number in range(1,5):

It should print "Hello" 4 times. Another type of loop is a while loop. Here's an example

while number < 5:

It should print the integers from 1 to 4 inclusive. Each time the code goes round the loop, the value of number is checked, its value is printed out, then 1 is added to it.

[show extra information]

Decisions    [ back to contents]

The while line above involved a comparison whose outcome affected the course of the program. As well as using < (meaning 'less than') to compare values you can use

  • <= (meaning 'is less than or equal to')
  • (meaning 'is greater than')
  • >= (meaning 'is greater than or equal to')
  • != (meaning 'isn't equal to')
  • == (meaning 'is equal to').

There's also an if keyword. Here's an example

if num<5:
     print ("num is less than 5")

Train yourself to use == rather than = when making comparisons (some languages use === so count your blessings). Be careful to avoid mixed-type comparisons - if you compare a floating point number with an integer the equality tests may not work as expected.

You can use else in combination with if - e.g.

if num<5:
     print ("num is less than 5")
     print ("num is greater than or equal to 5")

You can combine comparisons using boolean logic. Suppose you want to run a line of code if num is between 3 and 5. You can use

if 3<num and num<5:
   print ("num is greater than 3 and less than 5")

As well as and, the Python language understands or and not.

Importing Modules    [ back to contents]

You've already used some of Python's functions - len and range. As we'll see later, many more exist in standard Python, but some of the most useful ones are in add-ons called Modules. Each of these modules tends to deal with a particular topic. Some are very specialised and especially useful for engineers. In this section I just give you a taste of the possibilities available. You don't need to try then all out now. You can probably guess what most of these lines do. What you will need to appreciate is that

  • to use a function in a module you first need to import the module
  • when you call the function you need to say which module (or submodule) the function comes from using the dot syntax - see the examples below
  • you'll need to read the documentation in order to use a module
import time
print (time.asctime(t))

import math

import cmath

import random
random.randint(1, 6)

import turtle

Writing Functions    [ back to contents]

You can write your own functions. The limits on their names are much the same as the limits on variable names. Here's a function that will print its input parameter three times

def tripleprint(s):
    for i in range(1,4):

Once you've typed this in, then you can try it out by typing




tripleprint needs one input argument which inside the function is called s in this example. In fact, s can only be accessed from inside the function - it's a local variable rather than a global one. If you had a variable s elsewhere the 2 variable wouldn't "clash".

Let's now write a function that prints its first input parameter as many times as we want

def multiprint(s, howmany):
    for i in range(1,howmany+1):

Now multiprint("hello", 7) will print "hello" 7 times.

These 2 functions don't "return" any values - i.e. they're not like sin or sqrt which supply an answer. Here's a function that returns double the number given it. It uses the return keyword to specify the value to be returned.

def doubling(s):
    return 2*s


The following table shows how Python represents various types of function diagrams

PythonFunction diagram
[show extra information]

Writing programs    [ back to contents]

hand All the examples so far have been short. Now you're going to write complete programs and save them. From the "Python Shell" window's File menu, choose "New Window" and type the following into it

# A program to simulate rolling a die 10 times
import random
def rolldie():
   return random.randint(1,6)

for i in range(1,11):
    print ("On roll ",i," I threw a ",rolldie())

The first line of this is a comment - the # symbol and anything to the right of it is ignored when the program is run. The last line uses the print command to display some strings, variables and function values. Note how commas are used to separate the values being printed out. Spaces are automatically added between the values.

Save the code as (Python files usually have the suffix py) then pick the "Run Module" option from the "Run" menu to run the program. You should get a list of dice throws like this.


Errors and Warnings    [ back to contents]

Testing can only prove the existence of bugs, not their absence - Dijkstra

You may not get everything right first time. Don't be worried by error messages - even the smallest spelling or punctuation error can break a program. You can get a lot of error messages from just one mistake so just look at the first error message.

The most common errors will be due to spelling mistakes, variables being read before they've been created, missing or incorrect punctuation, or incorrect indentation. When you think you've identified the trouble, correct it, save the file and run it again.

Even if your code is legal, it may do the wrong thing - perhaps because you've put a '+' instead of a '-'. One of the most effective things to do in this situation is to use print to print out the values of certain variables to help you diagnose where the problem is. Don't just passively stare at your code - make it print out clues for you.

Python has a help function but you might not find it very helpful initially. It will tell you about the thing you give it, so you can do help(len) to find out about the len function. If you do i=9 and then help(i) you'll be told more about i than you probably want to know. Perhaps most useful is a bookmark to a page like The Python Tutorial

[show extra information]

Input    [ back to contents]

To get input from the user, use something like

var = input("Type a number! ")

This will display "Type a number! " on the screen and put the user's reply into the variable (var in this example). This reply will be a string, so even if they type a number in, you won't be able to perform calculations with it. To convert it into an integer you can do this

var = int(var)

Exercise 1 - Adding    [ back to contents]

You now know enough to write your own programs. Use the "New Window" option to create a new file. Save it as Write a program that prints the sum of 2 numbers typed in by the user. Print an output line looking rather like this

   The sum of 6 and 73 is 79

Exercise 2 - Adding positive numbers    [ back to contents]

Create a new file called This time keep asking the user for input until they've typed in 2 positive numbers. I suggest that you start by copying then put each raw_input command inside a while loop so that you can keep on asking for input while the variable isn't a positive value.

Arithmetic    [ back to contents]

Use + (add), - (subtract), * (multiply), / (divide), and % (modulus - i.e. getting the remainder in integer division). Note that the operator for exponentiation is ** (beware: in some other languages 3^2 produces 9 but in Python it produces 1). The order of execution of mathematical operations is governed by rules of precedence similar to those of algebraic expressions. Parentheses are always evaluated first, followed by multiplication, division and modulus operations. Addition and subtraction are last. The best thing, however, is to use parentheses (brackets) instead of trying to remember the rules.

You can't omit * the way you can with algebra. For example you have to use 2*y to find out what 2 times y is. 2y is illegal.

If you try 5/2 you'll get the answer 2 because when an integer is divided by an integer, the result is an integer. If you do 5.0/2 or 5/2.0 you'll get the answer 2.5

[show extra information]

Exercise 3 - Times Table    [ back to contents]

Use the "New Window" option to create a new file. Save it as With a loop print out the first 10 entries in the 7 times table - i.e.

1 x 7 = 7 2 x 7 = 14 ... 10 x 7 = 70

(don't worry too much about putting the spaces in exactly the right places)

Exercise 4 - Times Table Function    [ back to contents]

Write a function called timestable that will print the 7 times table that you had before. Write it so that you can use timestable(7) to run it. Check that timestable(9) produce the 9 times table.

Exercise 5 - Die throwing    [ back to contents]

You've already been shown a function that simulates the throwing of a die. Roll the die a 1000 times to see how many 6s are thrown. Print the answer out.

You'll need a variable to store how many sixes are thrown. Initialise it to zero and add 1 to it each time a 6 is thown.

Exercise 6 - More Die-throwing    [ back to contents]

This time you're going to keep a count of all the outcomes, not just the 6s. Print the results out like this

1 was thrown 0 times 2 was thrown 23 times ...

You'll need a variable to store the frequencies of each of the outcomes. Rather than name these variables ones, twos, etc (which gets messy, especially when we start using several dice) I suggest you use a list. The following code creates a list called frequency and then sets all the elements to 0 (even frequency[0], which we're not going to use).

# the next line creates a list of 7 items initialised to 0

If you use frequency[1] to store the number of 1s thrown, frequency[2] to store the number of 2s thrown, etc, you can use a loop to print out these values at the end.

Exercise 7 - Throwing 2 Dice    [ back to contents]

Write a function that simulates the throwing of a pair of dice and returns their sum. Roll the dice a 1000 times and display the frequency of the outcomes similar to the previous exercise.

Reading from files    [ back to contents]

f = open('workfile', 'r')

opens a file called workfile ready for reading.


reads a single line from the file; a newline character (displayed as \n) is left at the end of the string

Using these 2 commands you can do the following to get a line of text from a file (in this case a file called secretmessage) and put it into a string (in this case called message).


There are many other file-reading facilities, but that's all you'll need for now.

[show extra information]

Exercise 8 - Code Solving (reading files)    [ back to contents]

In your Python folder (created when you did start python) there's a file called "secretmessage" (download this file if you don't have the original). Your mission is to write a program called to decode the contents of this file (a single line of text). It's been encoded using a simple shifting algorithm where each letter has been replaced by the letter N places behind it in the alphabet ("Z" being treated as the letter before "A"). Spaces haven't been encoded, and there's no punctuation. Just try to decode the message, determining the appropriate N by trial and error. The message is in upper-case letters. Break the task into stages, checking as you go

  • Using the code in the previous section, read the message in from the file into a string using readline (the message is only one line long). Create an integer N (the amount the characters have been shifted by) and set it to a value. For now, let's just guess the number 7.
  • You can use the string as if it were a list of characters. Pick out the characters in the string one at a time using a loop like this
    # while we're not at the end of the string, get the character
    while characters_processed < len(message):
    Each character is represented in the computer as an integer. The ord function returns that integer so that you can perform arithmetic on it (ord('A') for example returns 65).
  • Inside the while loop, process each character stored in the letter variable
    • If the character is not a space, set letter to be letter plus N. If the resulting character is more than 'Z' (i.e, if letter > ord('Z'):), subtract 26 from letter so that the letter cycles round.
    • Convert the resulting integer back into a character using the chr function and print the resulting string out (if you add , end="" to the print command's argument - i.e. use print(chr(letter), end="") - then all the characters will appear on the same line)

Run the program. If you're lucky you'll get a readable message. It's more likely that you'll get junk because N will need to be a different number. Rather than manually having guess after guess (changing N and running until you get the answer) try this

  • Restructure the code to make it neater. This is something developers often have to do - re-engineer their work so that it does the same as before, but in a tidier way. Put the decoding code you've written into a function called decode_and_print that takes the coded message and N as its input parameters, returning nothing. Its job is to print the decoded message. Once you've written the function, all that your main code need contain is the code to read the message in, then a call to the function by doing decode_and_print(message,7). You should get the same result as before!
  • Change the program so that it tries decoding with N=1, then N=2 up to N=25. printing the decoded message each time. Do this using a loop. Determine the N that works for your message.

Exercise 9 - Pi (math functions)    [ back to contents]


You can calculate pi just by dropping a pen, as long as you drop it onto floorboards several times. If the pen is as long as the floorboards are wide, then pi will be roughly


The pen will hit a crack (an edge of a floorboard) if the closest distance (D) from the pen's centre to a crack is less than or equal to 0.5 times sin(theta), where theta is the angle between the pen and the cracks.

This gives us the chance to do a simulation (a common task in engineering). Don't try to write the complete program before trying to build it. Take it stage by stage.

  1. In a file called write a function called dropthepen to simulate the dropping of the pen. Make it return True if it touches a crack in the floor and False otherwise.
    There are 2 random factors to take account of - the angle of the pen (0 - pi/2 radians) and the distance of the pen's centre from a line (0 - 0.5; our floorboards will be 1 unit wide). The function will need to calculate sin(theta). The sin function expects its argument to be in radians so you can do
    Create a variable D and set it to random.uniform(0,0.5).

    Using D and sin(angleinradians) you can now work out whether the pen lands on a crack.
  2. Add some code to call your function. Use a loop to call dropthepen 10 times. Does the function seem to be working ok? How many times do you expect the pen to touch a crack? If it touches 0 or 10 times, your code is probably wrong.
  3. Before the while loop, create a variable (numberOfHits, say) to store the number of times the pen crosses a crack. Initialise it appropriately. Inside the while loop, add 1 to it when the dropthepen function returns True. After the while loop, write the code to estimate pi.
  4. Now do 10,000 runs. You should get a more accurate answer for pi.

Exercise 10 - Monopoly ©    [ back to contents]

You're playing Monopoly. First the good news - you've landed on GO so you get £200. Now the bad news - there are 5 hotels along the first side of the board and you own none of them. What chance do you have of reaching the 2nd side without landing on any of the hotels? What's the most likely number of hotels that you'll land on?

You could solve this using probability theory. We're going to do it "by experiment", writing a program called to run 10,000 simulations.

Whenever you have a non-trivial program to write, think about how it can be broken down into stages, and how you can check each stage.

  1. You already have a function to roll 2 dice. Write a function to simulate a single user's attempt to get past the hotels. Call it runTheGauntlet unless you can think of a better name. It won't need any inputs, but it needs to return the number of hotels landed upon. Think first about your strategy in words (draw flow charts if you want), then express that strategy using Python. It helps to have a variable (called location, say) that records where you are. First set a counter hotelsVisited to 0. You need to keep rolling the dice until you've gone past the 9th square (so use a while loop). Each time you move, check to see whether you've landed on a hotel. If you have, add 1 to hotelsVisited. At the end of the function return hotelsVisited. Test this function - run the function a few times and print the outcome to see if the results are reasonable.
    To see whether you've landed on a hotel, you can create a list of hotel locations
      hotelLocations=[ 1, 3, ....]
    then use
      if location in hotelLocations:
    to see if you've been unlucky.
  2. Now call that function 10,000 times using something like
    in a loop. You don't want to print each outcome but you do want to store how many times no hotels were landed on, how many times only 1 hotel was landed on, etc. Create a list called frequency to store the results. frequency[0] will contain the number of runs when no hotels were landed upon, so for each run when no hotels are landed on you need to add 1 to this value. When you've done all the runs, frequency[0] will contain the final value. You need to deal similarly with the other elements of the array. How many elements will this array need? What should the initial value of each element be?
  3. Using a loop, print the summary of results on the screen.
      Hotels-visited  Frequency   Percentage

Note: On each turn in Monopoly, 2 dice are thrown and their sum used to determine how far a player's counter moves. If the GO square is counted as position 0, then the hotels are located on positions 1, 3, 6, 8 and 9 along the first side. In the Cambridge Edition of Monopoly, the properties along the first edge are (in order) "Histon Road", "Parker's Piece", "Hills Road", "Cheddars Lane" and "Bateman Street". As an extra challenge you could find out which property you are most likely to land on.

New Types    [ back to contents]

If the range of types that Python provides is too restrictive you can invent new types. When you use a language (like English or Python) you are often attempting to represent or model the real world. The more the modelling language structurally resembles what it's modelling, the easier the modelling is likely to be. Suppose you have the following data

    Name     Anna Smith   Ben Crab   Charlie Webb
    Height   177          185        170
    Age       20           18         15

You can create a class (a new type) designed to contain this information as follows

   class Person:

The values provided here are defaults for the properties you've created. You could then create a variable to represent Anna's information by doing

   anna.fullname="Anna Smith"

The variable anna "has" a fullname, height, and age just as the person Anna has a name, height, and age. If you wanted to print Anna's height later on, you could do

print ("Anna's height = ", anna.height)

Here's another example. Suppose your program was dealing with 2-dimensional points. It would help to have a type of variable to represent a point. You can create such a type like this

   class Point:

Inside Point there are x and y coordinates, initialised to 0. If we wanted to create a function to display the coordinates of a point we could produce this

   def display(thePoint):

Then the following would work


But it's a good idea to keep this routine and the class it depends on together because they depend on each other. In big programs especially, this approach (the Object Oriented approach) is recommended. To illustrate this, here's an alternative way of defining the Point class.

   class Point:
     def display(self):

The display function now belongs to the class (it's known as a member function). self is a special argument - it means that the function uses items inside the object it's part of. The following code fragment shows how to set p's component fields to values and print them out using this member function

[show extra information]

Writing to files    [ back to contents]

To write to a file first you need to open it by doing something like


then you can use


to write the contents of a string str to the file, To write something other than a string, it needs to be converted to a string first. For example, you can do

value = ['the answer', 42]
s = str(value)

When you've finished with a file it's a good idea to close it using


Python for Engineers    [ back to contents]

With Python you can quickly write little programs, but as engineers you'll be writing big or specialised programs before long. You might find these modules especially useful. If they're not already on your machine you can install them.

  • Numpy is the defacto standard for the work with arrays (which are like lists except that all the items need to be the same type, and they're faster) and linear algebra. We don't have these installed, but we have some earlier modules. Here's an example
    import numpy as np
    a = np.array (( (1, 5, 6), (7, 4 ,2), (0, 2, 8)))
    b = np.array (((4), (2), (5)))
    print ("a=",a," b=",b)
    print ("determinant=",np.linalg.det(a)) 
    c=np.linalg.solve(a, b)
    print ("Solution of ax=b is ",c)
  • Scipy deals with statistics, optimization, ODEs, etc.
  • matplotlib creates graphics. Here's an example
    import matplotlib.pyplot as plt
    import numpy as np
    a = np.zeros(1000)
    b = np.fft.fft(a)
  • sympy helps with symbolic integration, etc. Here's an example
    from sympy import *
    x = symbols('x')
    a=integrate(x**2 * exp(x) * cos(x), x)
  • EasyGui produces buttons and menus. Alternatively you can use wXwidgets (as used in 3rd year projects) or Tk.

On linux you don't need to run idle to write or run a python program. Just typing python on the command line will type an interactive version of python, and you can use any text editor to write your programs.

You can make your programs run just by clicking on them if you want

  • Add
      #! /usr/bin/python
    to the top of your file
  • Make the file executable ("runnable") by clicking on it with the right mouse button, choosing "Properties" and clicking on the "Execute" box (see the illustration on the right).

You can then use the file almost as if it were a compiled C++ program.

Storing your Functions    [ back to contents]

If you've written a useful function you might want to use it again and again. Rather than copying it into each program you need it in, you can save it in a file and import it. Here's an example

In the folder where you're working, create a file called and put the following into it

def tripleprint(s):
    for i in range(1,4):

def multiprint(s, howmany):
    for i in range(1,howmany+1):

Now from the command line (or a program) you can load and run that code by doing

import extras

Note that import won't look around everywhere for modules. It looks

  • In the current folder
  • In PYTHONPATH - a list of folders you can customise
  • In the system's default folders (do import sys; print sys.path to list them)

You'll need to set PYTHONPATH before you start Python. In Linux or MacOS you can do something like

export PYTHONPATH=/home/tim/mypythonmaths:/home/tim/mypythonpix

In Windows you can do something like

set PYTHONPATH=c:\python20\lib;

More Features    [ back to contents]

As your programming skills and requirements grow, Python can grow with you. Here I'll just mention a few extra features

Doing without loops - Python offers several ways to avoid using for or while. There are functions to perform tasks that in some other languages require loops - try

  x.index(7) # find the value '7' in x

There's also the filter routine. Given a list of items and a function that returns True or False depending on whether you want to keep an item, filter will filter out the unwanted material.

def multipleOf7(num):
   if num%7==0:
      return True
      return False


Dictionaries - When lists aren't powerful enough you can try dictionaries. A dictionary is a collection of paired values - an English word and a French word, for example, or a name and a phone number. They're useful whenever you want to look up something. The following code creates a dictionary, uses it to look up the boiling point of water, then prints out all the information

  boilingPoints={"Methane":-164, "Water":100,"Mercury":356.9}
  for substance, temperature in boilingPoints.iteritems():
     print (substance," boils at ", temperature," C")

More exercises    [ back to contents]

You can practise by trying some of the exercises below. The earlier ones are easier.

  • Write a function that prints the primes less than 100. Use for loops rather than while loops.
  • Write a function that given an integer prints out its prime factors. Use for loops rather than while loops.
  • Write a function that given 2 integers prints out their highest common factor
  • Write a function that given 2 integers prints out their lowest common denominator
  • Pick a number. If it's even, divide by 2. If it's odd multiply by 3 and add 1. Continue this until you reach 1. E.g. if you start with 3, the sequence will be 3-10-5-16-8-4-2-1. Write a program to find out which integer less than 100 produces the longest chain.
  • Ask the user to type an integer in the range 1 to 7. If the user types something invalid, ask them to try again. Then print the day of the week corresponding to the number - print "Sunday" if the user types 1, etc.
  • The zeta function, zeta(s), can be evaluated by summing terms of the form 1/is for i running from 1 to infinity. It can also be evaluated by multiplying terms of the form (1/(1-1/ps)) where p runs through all the primes. See how true this is for series of 10 terms then 100 terms.
  • Simulate a situation where you keep asking different people their birthdays until you find 2 people with the same birthday. Assume all years have 365 days. Make the code into a function so that you can run it many times and find an average for the number of people you need to ask.
  • Big numbers are often printed with commas after every 3 digits - e.g. 1,345,197. Write a function which is given a float and prints out the number with commas. You'll need to find out how to convert numbers to strings - use the WWW!
  • Create a list to represent an 8x8 chessboard. In chess a Bishop can move as far as it likes along diagonals. Write a program to count the number of places a Bishop can move to for a particular starting position. From which starting positions does it have the greatest choice of moves?
  • In chess, a knight moves in an 'L' shape (2 squares along a row or column, then one square left or right). Write a program to count the number of places a Knight can move to for a particular starting position.
  • Starting at any square on a chessboard, move the knight randomly, and keep moving until it lands on a square it's already visited. How many moves does it do on average?
  • Write a function that adds 2 vulgar fractions and prints their sum as a vulgar fraction so that calling it as addfractions(3,4,5,6) will make it output something like 38/24, or better still 19/12, or even 1 + 7/12. You could create a class called Fraction
  • Using the turtle module draw a square. Write a function that draws a square. Write a function that draws a * to the size you request.
  • Python has function to sort items. We'll investigate how the time taken to sort items depends on n, the number of items. Is the time proportional to n? Here's a program that has some timing code in it
    #! /usr/bin/python
    from datetime import datetime
    import random
    def microseconds():
       dt =
       return dt.microsecond
    for i in range(0,thelength):
    for i in range(0,thelength):
    print ("    Length      Time    Time/n   Time/(n*ln(n))")
     print (repr(thelength).rjust(10))
    The microseconds function returns the number of microseconds that have elapsed since 1st Jan 1970. Don't worry about how it works. When you run this code you'll see a list of unsorted numbers, a list of sorted numbers, then part of a table. The final line prints thelength out so that it's right-justified in a column of width 10. First, comment out the lines that print the numbers (later you won't want to watch 10,000,000 numbers being printed out). Then complete the line of the table by timing the sort function (call microseconds() twice and find the difference between the 2 results). Time only the sort function - don't time the setting-up code too. Then complete the final 2 columns of the table. Your output should be something like

        Length      Time    Time/n   Time/(n*ln(n))
            10         82 8.1999999999999993 3.5612147516066646

    Then using an appropriately placed loop add a completed line of data to the table for lengths of 100, 1000 ... 10,000,000. You'll need to move the line that prints the column headings so that they only appear once.
  • Find out on how many lines of this Web page's source code the word Python is mentioned. Here's some code to get you started
    import re     # to search for a string on a line
    import urllib # to get the web page
    f = urllib.urlopen(url)
    for line in f.readlines():
        match ='Python', line)
        if match is not None:
           print (line)
    Write a function wordInURL that given a word and a URL will display how many lines contain that word. For example wordInURL("iPad", "") might produce
    iPad is on 5 times
  • The following code (which uses a dictionary and recursion) defines a network of points and connections, then finds a route from A to D. Write a function to find all the non-cyclic paths. Write a function to find the shortest path
    graph = {'A': ['B', 'C'],
                 'B': ['C', 'D'],
                 'C': ['D'],
                 'D': ['C'],
                 'E': ['F'],
                 'F': ['C']}
    def find_path(graph, start, end, path=[]):
            path = path + [start]
            if start == end:
                return path
            if not graph.has_key(start):
                return None
            for node in graph[start]:
                if node not in path:
                    newpath = find_path(graph, node, end, path)
                    if newpath: return newpath
            return None
    find_path(graph, 'A', 'D')
    (answers are on the Python Patterns - Implementing Graphs page)
  • For the lines below try to explain why the 2nd line of output isn't the same as the 1st, and why the 3rd line of output isn't the same as the 2nd
      4.0/3.0 -1.0/3.0 -1.0
      4.0/3.0 -1.0 -1.0/3.0
      4/3     -1   -1/3

Real programs    [ back to contents]

The difference between a beginner's program and a commercial program can be huge - even if you were allowed to see the source code of "Word" you wouldn't understand it. But some Python programs are useful and short. If you're on a Mac or a Linux machine (the CUED central system machines, for example) you'll have some Python programs on the system. You can list them from the command line by doing ls /usr/bin/*.py. Because Python is a scripting language, these files are readable text - like the programs you've been writing. Some are short enough for you to have a chance of understanding part of them.

[show extra information]

Useful Links    [ back to contents]