Department of Engineering

IT Services

Python by Example

Introduction

Python is a free, interpreted language with support for Object-Oriented work. If you know matlab, perl or Java you'll have met most of the concepts used by Python. On the teaching system you can run it by opening an XTerminal window and typing /usr/local/apps/anaconda3/bin/python (the default python on the system is Python 2, but we're going to use Python 3). The prompt at the start of the command lines is >>>

This document aims to give you a feel for the language by giving you some sample commands to type in. Without knowledge of perl, Java or matlab, some of the underlying concept might be difficult for you: at the end of this document are some sources of further information.

Variables

You needn't create them and specify their type before assigning values. The following commands work

>>> x=1 >>> y="hello"

You can use the print function to see a variable's value. Python has ways of collecting elements together. The elements needn't always be all of the same type

  • strings - str="hello"
  • tuples - a=(1,"five",2)
  • lists - a=[1,"five",2]
  • dictionaries - a={1,"five",2}

strings, tuples and lists are ordered sequences (like arrays). strings and tuples are read-only ("immutable"). Dictionaries are sets of key:value pairs. By default the keys are 0, 1, ... in which case the dictionary is like an array, but a dictionary can be like a "map" in Java/C++, so the following will produce "ted"

>>> dict={"dad":"ted","mum":"flo"} >>> print(dict["dad"])

Assigning a value to a variable sometimes creates a new object, and sometimes creates an alias

>>> a="foo" >>> b=a >>> print(a,b)

gives

foo foo

If you then do

>>> print (id(a), id(b))

you'll find that a and b refer to the same underlying object. However if you then do

>>> a="bar" >>> print (a,b) >>> print (id(a), id(b))

you'll find that a and b now refer to different objects that have different values - a, a string, is immutable, so a="bar" forced the creation of a new object. Contrast that with the following situation

>>> x=[ 1, 2, 3] >>> y=x >>> print (x,y)
[1, 2, 3] [1, 2, 3]
>>> x[1]="middle" >>> print (x,y)
[1, 'middle', 3] [1, 'middle', 3]

Here x is a list, so it's "mutable" and can be changed.

a == b will tell you whether the 2 variables have the same value. a is b will tell you whether the variables refer to the same object.

Multiple assignments are possible, with the elements of one list being assigned to another. That makes the following possible

>>> x =1 >>> y =2 >>> x,y = y,x # equivalent to [x,y]=[y,x] >>> print (x,y) # by the way, comments begin with a '#'

Comparisons

The operators are similar to those in other languages, though note that the following chained expressions have their expected mathematical truth values (in C++ they're legal but the expressions have different meanings)

>>> 6<5<4
False
>>> 6>5>4
True

Operations

All the usual mathematical operations are possible, and much more besides.

>>> x=[ 1, 2, 3] >>> 3 in x
True
>>> 4 in x
False
>>> max(x)
3
>>> len(x)
3
>>> heads = [0]*10 >>> print(heads)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> s="foo" >>> t = s*3 >>> print(t)
foofoofoo

The range command creates a list

>>> a=range(1,10) >>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Slicing operations extract elements from sequences. You give the index of the first element you want (indexing starts at 0) and the index of the first element you don't want. For example

>>> s="foo" >>> print(s[1:3])
oo

You can replace a slice. Try

>>> s=range(1,6) >>> s[1:3]=[ 7, 7] >>> print(s)

You can set alternate elements to particular values. Try

>>> s[::2]=range(97,100) >>> print(s)

You can remove slices. Try

>>> del s[3:5] >>> print(s)

Conversions

print(4+2) works, so does print("x" + "2"), but

>>> print("x" + 2)

won't work - you'll get something like

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

You need to convert one of the objects by doing (for example)

>>> print("x" + str(2))

The list command converts a string/tuple into a list - useful because a list is mutable. The following converts a string into a list (so that the characters can be sorted in-place), then converts the list back into a string using a member function (to find out what a member function is, see later)

>>> t="cabbages" >>> t=list(t) >>> t.sort() >>> t="".join(t) >>> print(t)

Modules and scripts

So far we've been working from the command line. If on a unix machine you put commands into a file, make the file executable (by typing chmod u+x filename) and put

#! /usr/local/apps/anaconda3/bin/python

as the first line of the file, you can run the file (if the python program exists at /usr/bin/python). Comments in a script begin with a #. For some of the longer examples that follow, it's assumed that you'll write a script rather that enter the lines interactively, so the command-line prompt won't always be shown.

python "add-ons" are called modules. You need to "import" a module. For example,

>>> import math

will load a math.py file that's on the system, giving access to sqrt etc.

The sys module lets you provide arguments to scripts. sys module lets you access these arguments. In a script, the following lines will print the first argument given to the script

import sys print (sys.argv[1])

Functions

To create a function that returns twice what it's given, do

>>> def myfun(i): >>> return i*2

Then a=myfun(3) would set a to 6. Note that indentation is significant - the end of the routine is where indentation ends.

Classes

The objects so far created are objects which have member functions. Here are some examples of use

# the next line run the string's rstrip member # function to strip off spaces from the right >>> "jjj ".rstrip() >>> s="foobar" >>> s.count("o") >>> s.find("ob") >>> s.replace("o","u") >>> s.reverse()

Dictionary objects have several specialised routines

>>> dict={"dad":"ted","mum":"flo"} >>> dict.values()
['ted', 'flo']
>>> dict.keys()
['dad', 'mum']
>>> dict.items()
[('dad', 'ted'), ('mum', 'flo')]
# removes and returns a random item >>> x=dict.popitem()

You can also define your own classes, and inherit from existing classes. The following creates classes called 'foo' and 'fooplus'. __init__ is the constructor (as in C++ and Java). Default values can be set similar to the way they are in C++ - here, num is 3 by default. Note that member functions need to explicitly state which object they're acting upon, but when you call a member function you don't mention the object as a parameter

class foo: def __init__(self, num=3): self.x=num def doublit (self): self.x=self.x*2 # this creates a new class 'fooplus' which # inherits from foo and adds new members class fooplus(foo): y=7 def printme(self): print (self.x,self.y) # now create an object of type 'foo', # setting its x to 9 afoo=foo(9) print (afoo.x) # create an object of type 'fooplus'. Its x will # initially have the default value of 3. afooplus=fooplus() print (afooplus.x) afooplus.printme() print (afooplus.doublit()) afooplus.printme()

If a variable is within a class but outside all member functions, then it is shared by all objects of that class.

Control flow

Python has all the usual control flow options - again, indentation is significant

if (a==1): print(a) else: print("a is not one") for x in range (1,6): print(x,x*x) a=1 while a<10: print(a++)

Files

The file-handling commands are similar to other languages

f=open("aaa","r") # open a file for reading s=f.read(3) # read 3 bytes s=readline() # read a line # get a number from the user number=input("What's your lucky number? ")

System commands

The os module lets you find out about the computer

import os dir=os.getcwd() # find the current directory os.system("date") # run a command # get the files in the current directory for f in os.listdir(dir): print(f)

Exceptions

Like several other languages (C++, Java, etc), Python lets you use exceptions to deal with errors. The following code works

print ('answer=%d' % 7)

producing

answer=7

(Python's print command is behaving rather like C's printf) but if you try

print('answer=%d' % 'string')

you'll get

TypeError: %d format: a number is required, not str

If you run the following, you'll see that the error caused by the print command has been detected and a message of your choice has been displayed.

try: print ('answer=%d' % 'kkk') except TypeError: print 'wrong argument for print'

More technically, the print command raised an exception of type TypeError, which the except handler dealt with.

Misc

type(x) # this displays x's type

Info

Graphics