An Introduction to Python - PowerPoint PPT Presentation

About This Presentation
Title:

An Introduction to Python

Description:

I learnt a great deal by browsing the python web site and its linked pages. ... else: # Okay; have a tantrum! raise AttributeError, attribute ... – PowerPoint PPT presentation

Number of Views:210
Avg rating:3.0/5.0
Slides: 44
Provided by: harrison4
Learn more at: http://www.hep.fsu.edu
Category:

less

Transcript and Presenter's Notes

Title: An Introduction to Python


1
An Introduction toPython
  • Harrison B. Prosper
  • Florida State University

2
Acknowledgements
  • I learnt a great deal by browsing the python web
    site and its linked pages.
  • http//www.python.org
  • http//www.python.org/doc/tut/tut.html
  • Guido van Rossum (python author)
  • David Beazley (SWIG author, University of Utah)
  • Mark Lutzs excellent book.
  • Programming Python, OReilly Associates Inc.
  • Frederick Lundhs Tkinter documentation is very
    helpful.
  • http//www.pythonware.com/library.htm

3
Outline
  • Part I
  • What is python?
  • Getting started
  • Namespaces
  • Sequences
  • Functions
  • Classes
  • Odds and ends
  • Part 2
  • Graphical User Interfaces
  • A Simple GIF/JPEG/BMP Browser

4
What is python?
  • Python is a scripting language, created by Guido
    van Rossum (guido_at_CNRI.Reston.VA.US), that is
  • interpreted
  • object-oriented
  • dynamically typed
  • simple
  • powerful and
  • free
  • Python website
  • http//www.python.org

5
Getting started
  • The python interpreter has been ported to all the
    popular platforms, including Windows 95/NT.
  • Running python interactively
  • setup python
  • python
  • gtgtgt print Thou lump of foul deformity
  • Thou lump of foul deformity
  • gtgtgt x 2 y 5
  • gtgtgt z xy
  • gtgtgt z
  • 10

6
Example 1 (from, import, for, in, if, else)
from string import atoi, split Add atoi, split
to global namespace. import os Add os to
global namespace. f os.popen(cd ls
-l) Pipe command output to file. s
f.read() Read into a single string. l
split(s,\n) Split into a list of strings. n
len(l) Get length of list. for j in
xrange(n) Iterate over a range object. a
split(lj) Split into a list of strings. if
(len(a) gt 4) If length of list gt 4
convert size atoi(a4) string value into
an integer. print size, lj else LOOK MA,
NO BRACES BECAUSE print lj PYTHON USES
INDENTATION!
7
Namespaces
__builtins__
len, xrange, dir, open,...
Global (import)
__builtins__
os
f, s, atoi, split l, n, j, a, size
popen, system, listdir, environ, path,...
8
Looking at namespaces
l dir() Create a list of the names for j in
xrange(len(l)) in the global namespace print
lj l dir(__builtins__) Create a list of
the names in the namespace of the
module __builtins__ l dir(os) Do
likewise for the module os
9
Example 2 (map, lambda)
l dir(__builtins__) List names in module
__builtins__ o map(lambda x x\n,l) For
every element x of list apply the one-line
function f(x) x\n and return the
result in the list o. f open(builtins.txt,w)
Open a file object f for output. f.writelines(o
) Write out list of newline-terminated
strings. f.close() Close file object. from
string import strip Add strip to global
namespace. g open(builtins.txt,r) Open
file for input. t g.readlines() Read entire
file into list t. t map(strip,t) Strip off
whitespace (here newline).
10
Example 3 (filter)
from string import strip, find Import strip and
find t open(builtins.txt).readlines() Read
entire file into list t. t map(strip,t)
Strip off whitespace. o filter(lambda x
find(x,Error) gt 0, t) For every x in list
t apply the one-line function f(x)
find(x,Error) gt 0 If f(x) is true
(i.e., f(x)1) copy x to output list
o. Example of python error code
AttributeError
11
Sequence types
  • Immutable types (cant be changed)
  • Strings aString Go boil your head
  • Tuples aTuple (Bozo,42,3.14,aString)
  • Mutable types (can be changed)
  • Lists aList aString, aTuple,1997
  • Dictionaries aMap stringaString,(1,2)aList
  • General operators on sequence s
  • len(s), min(s), max(s), si, sij (
    si..sj-1)
  • x not in s 1 if item x not in s, else 0
  • s t concatenate sequences s and t
  • ns n copies, concatenated

12
Tuples (immutable cant be changed)
0 1 2 3 4
5 gtgtgt IamAtuple (The,time,3.141,has,42,co
me) gtgtgt IamAtuple0 IamAtuple5 The come
gtgtgt IamAtupleSlice IamAtuple36 gtgtgt
IamAtupleSlice (has,42,come) gtgtgt
IamAtupleCopy IamAtuple gtgtgt
len(IamAtupleCopy) 6
13
Lists (mutable can be changed)
gtgtgt IamAlist The,time,3.141,has,42,come
gtgtgt IamAlist0 The gtgtgt IamAlist2
(1,2,3) IamAlist The,time,(1,2,3),has,42,
come gtgtgt IamAlist.sort() 42,The,come,has
,time,(1,2,3) gtgtgt IamAlist.append(1997)
IamAlist 42,The,come,has,time,(1,2,3),199
7
14
Dictionaries, or mappings (mutable)
gtgtgt IamAmap An empty dictionary gtgtgt
IamAmapAlso 1one,(2,boo)two gtgtgt
IamAmaplanguage (python,1997) Bind
keys to gtgtgt IamAmapcomment Superb!
values. gtgtgt IamAmapcost 0 gtgtgt
IamAmapmap IamAmapAlso gtgtgt
IamAmap.keys() Get list of keys cost,langu
age,comment,map gtgtgt IamAmap.values()
Get list of values 0,(python,1997),Superb!,1
one,(2,boo)two
15
Functions (def, None, return)
def goofy(a, byahoo,t, k) a is a
required arg. b is a req. arg. with a
default. t, k are optional args. r1
r2 None None is a python object. if (
len(t) gt 0 ) t is a tuple of args. r1
t0 k is a set of keyword args. if (
k.has_key(title) ) Check if key title
exists. r2 ktitle Get value for given
key. return (r1,r2) Return as a tuple. gtgtgt
a, b goofy(1,sucks,1,2, title2001,authorC
larke) gtgtgt print a, b 1 2001
16
Classes
class FourVector Name of class def
__init__(self, px0,py0,pz0,E0)
Constructor self.ok 1 Creation ok if E
gt 0 self.px, self.py, self.pz, self.e
px,py,pz,E else self.ok 0 Creation
failed def __del__(self)
Destructor pass gtgtgt p FourVector(12,-14,13,80
)
17
Classes, __str__ method
def __str__(self) Used by print and
str() s px d\n self.px Uses
the C printf s s py d\n self.py
format strings s s pz d\n self.pz s
s E d self.e return s Return
string Note We could also have written the
above as s s d\n
(px,self.px), etc.. gtgtgt print p px 12 py
-14 pz 13 E 80
18
Classes, __add__, __sub__ methods
def __add__(self, v) Implement u
FourVector() u.px self.px v.px u.py
self.py v.py u.pz self.pz v.pz u.e
self.e v.e return u def __sub__(self,
v) Implement -
19
Classes, __mul__ method
def __mul__(self, v) Implement u
self.pxv.pxself.pyv.pyself.pzv.pz return
self.ev.e - u gtgtgt p FourVector(1,2,3,10) gtgtgt
q FourVector(0,0,-1,20) gtgtgt pq pq
20
Classes, Inheritance
class Particle(FourVector) def __init__(self,
labele-,px0,py0,pz0,E0) Call
FourVector constructor to initialize px,
etc. FourVector.__init__(self, px,py,pz,E)
if self.ok Check for
success self.label label Create another
attribute else return NB Constructor return
value ignored def __del__(self) if self.ok
print Goodbye cruel world! else print I
never got properly made anyway!
21
Classes, dynamically created attributes
from math import Import all math
functions class Particle(FourVector) def
__getattr__(self, attribute) Method to get
values of dynamic attributes if
attribute mass x sqrt(self.e2 -(s
elf.px2self.py2self.pz2)) return
x else Okay have a tantrum! raise
AttributeError, attribute
22
Setting dynamically created attributes
class Particle(FourVector) def
__setattr__(self, attribute, value) Method to
set values of dynamic attributes if
attribute version NB Do not write
self.version value here because this
would create a statically defined attribute! Set
using the objects dictionary
attribute self.__dict__attribute
value else raise AttributeError, attribute
23
A simple Internet server
from socket import from os import def
server(PORT50000) Choose any non-privileged
port HOST Local host s
socket(AF_INET, SOCK_STREAM) Create
socket s.bind(HOST, PORT) Bind socket to local
host s.listen(1) Allow only a single queued
connection client, address s.accept() Wait
for a connection while 1 Wait
forever data client.recv(4096) Get up to
4k bytes if data quit break else
print data print Goodbye from server!
24
A simple internet client
from socket import from os import def
client(HOSTgethostname(), Default is local
server PORT50000) Server port s
socket(AF_INET, SOCK_STREAM) Create
socket s.connect(HOST, PORT) Connect to
server while 1 data raw_input(Clientgt )
Get keyboard input if data quit break
else s.send(data) Send to
server s.send(quit) s.shutdown(2) Terminate
all pending I/O s.close() Close
connection print Goodbye from client!
25
And finally, a client/server session
Server gtgtgt from server import server gtgtgt
server() Go Boil your head! Goodbye from
server! gtgtgt Client gtgtgt from client import
client gtgtgt client(d02ka.fnal.gov) Clientgtgt Go
boil your head! Clientgtgt quit Goodbye from
client! gtgtgt
26
Odds and ends
Changing the python search path
on-the-fly import sys sys.path.append(harry/py
thon/tutorial) sys.path.append(harry/python/ex
amples) Spawning commands to the operating
system import os os.system(cd ls
-la) Debugging python scripts (type h for
help) from pdb import run run(p
FourVector(1,1,2,90))
27
Odds and ends (eval, exec, try, except)
Evaluating strings and updating current
namespace p eval(FourVector(1,1,2,90)) Execu
ting statements and updating current
namespace) exec(p FourVector(1,1,2,90)) Hand
ling errors gtgtgt s open(FourVector.txt,r).rea
d() gtgtgt try Try following statements and . .
. p eval(s) if an error (i.e., an
exception) occurs . . . except execute these
statements. . . . exec(s) Note Can also
catch specified gtgtgt print p exceptions with
the except keyword.
28
Graphical User Interfaces
  • Tk is a widely supported toolkit for building
    portable Graphical User Interfaces (GUIs). Its
    purpose is to hide the unbelievable horrors of X
    windows.
  • Tkinter is a python module that provides an
    object-oriented wrapping of Tk. It is available
    with the standard distribution of python on many
    different platforms, including Windows NT/95.
  • http//www.pythonware.com/downloads.htm
  • download self-extracting archive
    (py15-980706.exe)
  • double-click on file to install python
  • To load all of the Tkinter attributes and methods
    into the global namespace do
  • from Tkinter import

29
Event-driven programs
  • A GUI application is an example of an
    event-driven program. An application goes through
    two steps
  • Construct GUI layout and bind screen objects
    (widgets) to functions (callbacks).
  • Enter a wait loop and bind events to callbacks

Construct GUI layout WaitForEvent Decide which
callbacks to call Dispatch callbacks
30
Anatomy of a simple GUI
Entry
Root
Scale
Frames are containers for Tk objects
(widgets). Gui layouts are created by using
nested Frames into which useful widgets are
placed. The root widget provides (platform-depende
nt) window management.
31
GUI Example 1
from Tkinter import Add all names to global
namespace import os class Gui(Frame) Gui is
an extended Frame def __init__(self,
parentNone) Default parent is
root Frame.__init__(self, parent) Initialize
Frame self.b Button(self, textList
Directory, commandself.list,
fgred, bggreen) self.pack(sideTOP)
self.b.pack(sideLEFT) def list(self) os.syste
m(cd ls -la) if __name__ __main__
Gui.mainloop() Run as script
32
GUI Example 2
from Tkinter import Add all names to global
namespace from ScrolledText import
ScrolledText class Gui(Frame) def
__init__(self, parentNone) Frame.__init__(self
, parent) self.pack() self.config(reliefGROOV
E, bd2) self.master.title(Example
2) self.text ScrolledText(self) self.text.p
ack() if __name__ __main__ Gui.mainloop()
33
A couple of other widgets
o is object, p is parent widget, v is value o
Scale(p, orientHORIZONTAL, from_ 0, to 1000) v
o.get(), o.set(v) o Entry(p), x
StringVar() otextvariable
x o.bind(ltKey-Returngt, callback) x.get(),
x.set()
34
Python Imaging Library
  • We shall use this extension (by Frederick Lundh)
    to build a simple graphics browser (gbrowser.py)
  • Import modules
  • class Gui(Frame)
  • Constructor
  • Get a list of filenames
  • Loop over filenames
  • Create and store full graphics image in a
    dictionary
  • Create a button, attach a thumbnail image to it
    and bind button to the display method
  • Display
  • Paste full image to a label in a separate window

35
A Simple Graphics Browser
from Tkinter import import Image Load a
couple of PIL import ImageTk classes import
os, sys from string import find, rfind,
lower FILETYPES (.gif,.jpg,.bmp) BIG
(768,576) SMALL(80,60) Handle different path
delimiters between windows and UNIX if
sys.platform 'win32' DELIM "\\" \ is
the python escape character else DELIM "/"
To make UNIX happy -(
36
Graphics Browser, part 1
class Gui(Frame) Gui is an extended frame def
__init__(self, parentNone, path('.',)) Try
to get a listing of given path ( (.,) -- syntax
for 1-tuple) try files Create an
empty list for d in path path is a tuple of
directories l os.listdir(d) f
map(lambda x,ydydelimx,l) files files
f Concatenate lists except Come here if
listing fails print "Errror, bad
directory ", d sys.exit(1)
37
Graphics Browser, part 2
Get list of graphics files. Extract the last
4 characters of each string x in the list
files. Make lower case, then test if the
4-character string matches a string in the
FILETYPES tuple. gifs filter(lambda x
lower(xlen(x)-4) in FILETYPES, files)
Initialize inherited frame Frame.__init__(self,
parent, reliefSUNKEN, bd2) self.pack() self
.image Dictionary for images row col
0 For use with grid method Next we shall
loop over the GIF files and try to read each
one
38
Graphics Browser, part 3
for giffile in gifs Loop over graphics
files Extract file name gif
giffilerfind(giffile,DELIM)1 Search from
right Exclude duplicate images if not
self.image.has_key(gif) print "Reading ",
gif, Note comma to suppress NL Read GIF file
and create image try ig
Image.open(giffile) ig.thumbnail(BIG) self.i
magegif ImageTk.PhotoImage(ig)
39
Graphics Browser, part 4
Paste button b with a thumbnail version of
image. Note the use of lambda to pass context
information to the single callback
self.display ig.thumbnail(SMALL) 80
x 60 pixels b Button(self, imageImageTk.PhotoI
mage(ig), commandlambda sself, xgif
s.display(x))
40
Graphics Browser, part 5
Pack using grid method, which requires that we
give the row and column numbers of a matrix.
Make buttons expand in all directions
(NSEW) to fill available space. b.grid(rowr
ow, columncol, stickyNSEW) col col
1 Update column number if col 5 row
row 1 Update row number col 0 print
"" Complete print statement except
associated with Try (see part 3) print "
FAILED " Here if we fail to read file
41
Graphics Browser, part6
Method to display full image def
display(self, gif) top Toplevel() Create a
separate window top.title(gif) top.iconname(gi
f) Label(top,imageself.imagegif).pack()
Note Because we do not plan to do anything with
the label other than display it, we dont
bother to create a reference (a name) for the
label.
42
Graphics Browser, running it
Code added at the end to execute file if it is
run as a script, that is python gbrowser.py
dir1 dir2 ... if __name__
'__main__' if not sys.argv1 Check for NO
arguments and, if path '.' none, default to
working directory else path
sys.argv1 Get arguments root
Tk() Create Tk root widget
root.title('Graphics Browser') Gui(root,
path).mainloop() Enter event loop
43
The End
Python in action!
Write a Comment
User Comments (0)
About PowerShow.com