Professional Documents
Culture Documents
What Is Python?: Emphasis On Structure and Discipline Simple Problems ! Simple Programs
What Is Python?: Emphasis On Structure and Discipline Simple Problems ! Simple Programs
Workshop #4 SIGCSE 2003 Note: Named after Monty Python’s Flying Circus
John M. Zelle
Wartburg College
Comment convention "#" to end of line print <expr1>, <expr2>, ..., <exprn>
Pluses
# fibonacci.py less code clutter (; and {})
# This program computes the nth Fibonacci number eliminates most common syntax errors
promotes and teaches proper code layout
n = input("Enter value of n ")
print "The nth Fibonacci number is", cur Bottom-line: Good Python editors abound.
This is my favorite feature.
Traditionally, Python did not support ++, --, +=, etc. >>>"Hello, " + " world!"
’Hello, world!’
>>> greet[4:9]
Personally prefer to avoid these shortcuts in CS1 ’o Joh’
>>> greet[:5]
’Hello’
>>> greet[6:]
’John’
>>> len(greet)
10
inf.close()
outf.close() Minuses
Need to be aware of aliasing when objects are mutable
Note use of string methods (Python 2.0 and newer)
Variable Scope Booleans in Python
Classic Python has only two scope levels: local and global No Boolean type
(module level)
Conditions return 0 or 1 (for false or true, respectively)
Variable is created in a scope by assigning it a value
In Python 2.2.1 and later, True and False are defined as 1,
Global declaration is necessary to indicate value assigned 0
in function is actually a global
All Python built-in types can be used in Boolean exprs
callCount = 0 numbers: 0 is false anything else is true
string: empty string is false, any other is true
def myFunc():
global callCount None: false
...
callCount = callCount + 1
Boolean operators: and, or, not (short circuit, operational)
Decisions Loops
if temp > 90:
print "It’s hot!" For loop iterates over a sequence
for <variable> in <sequence>:
if x <= 0: <body>
print "negative"
else: sequences can be strings, lists, tuples, files, also user-defined classes
print "nonnegative"
range function produces a numeric list
if x > 8: xrange function produces a lazy sequence
print "Excellent"
elif x >= 6:
print "Good" Indefinite loops use while
elif x >= 4: while <condition>:
print "Fair" <body>
elif x >= 2:
print "OK"
else: Both loops support break and continue
print "Poor"
Loops with Else Sequence Operations on Lists
>>> x = [1, "Spam", 4, "U"]
>>> len(x)
Python loops can have an else attached 4
Semantics: else fires if loop runs to completion (i.e. does not break)
>>> x[3]
Somewhat esoteric, but often quite useful
’U’
>>> x * 2
I consider this an "advanced" feature [1, ’Spam’, 4, ’U’, 1, ’Spam’, 4, ’U’]
def getNums(): Dictionaries are a built-in type for key-value pairs (aka
nums = []
while 1:
xStr = raw_input("Enter a number: ")
hashtable)
if not xStr:
break
nums.append(eval(xStr)) Syntax similar to list indexing
return nums
Python looks for modules on a module search path In Python, Information hiding is by convention
All objects declared in a module can be accessed by importers
Names beginning with _ are not copied over in a from...import *
Default path includes Python library location and current
directory Pluses
Makes independent testing of modules easier
Path can be modified: Eliminates visibility constraints (public, private, static, etc.)
When Python is started (command line arg, env var)
Dynamically by the script itself (sys.path) Minuses
Language does not enforce the discipline
Related modules can be grouped into directory structured
Bottom-line: Teaching the conventions is easier
packages
from OpenGL.GL import * The concept is introduced when students are ready for it
from OpenGL.GLUT import * Simply saying "don’t do that" is sufficient (when grades are involved).
Dual function module--import or stand-alone program Objects in Python are class based (ala SmallTalk, C++,
if __name__ == ’__main__’:
runTests() Java)
def getValue(self):
return self.value
Peter Norvig: ’...a dialect of LISP with "traditional" syntax.’ List Comprehension Combines Mapping and Filtering
[<expr> for <var> in <sequence> if <condition>]
[lt for lt in someList if lt < pivot]
FP features
First class functions
Recursion
Reliance on lists Using Comprehensions for Quicksort
Closures def qsort(L):
if len(L) <= 1: return L
Python Functional Built-ins return ( qsort([lt for lt in L[1:] if lt < L[0]]) +
lambda <args>: <expr> --> <fn-object> L[0] +
map(<function>, <list>) --> <list> qsort([gt for gt in L[1:] if gt >= L[0]])
filter(<function>, <list>) --> <list> )
reduce(<function>, <list>) --> value
[<expr> for <vars> in <sequence> if <test>]
FP Example: Closures About Tkinter
Closure is a function that captures "surrounding" state Allows Python to Use TK Toolkit from TCL/TK
def buildMenus(self):..
def onSave(self):...
def onExit(self):...
Example Program: Simple Editor(cont’d) Example Program: Simple Editor (screen)
def buildMenus(self):
menubar = Menu(self.root)
self.root.config(menu=menubar)
filemenu = Menu(menubar,tearoff=0)
filemenu.add_command(label="New...", command=None)
filemenu.add_command(label="Open...", command=None)
filemenu.add_separator()
filemenu.add_command(label = "Save",
command=self.onSave)
filemenu.add_command(label="Save as...",
command=None)
filemenu.add_separator()
filemenu.add_command(label="Exit",
command=self.onExit)
menubar.add_cascade(label="File", menu=filemenu)
def onSave(self):
if not self.filename:
filename = asksaveasfilename()
if not filename:
return
self.filename=filename
file = open(filename, ’w’)
file.write(self.text.get("1.0",END))
file.close()
def onExit(self):
ans = askokcancel(’Verify exit’,
’Really quit?’)
if ans: sys.exit()
root = Tk()
root.title("Simple Editor")
Editor(root).mainloop()
Computer Graphics Baby Graphics: Triangle Screenshot
main()
PyOpenGL Example: GLUT Cone (Screen) Example Project: Chat Server
Three modules
chat server
talk client
listen client
Client-Server GUI
Chat Clients TCP Server Example: httpPeek
def talk(machine, port):
RESPONSE = """HTTP/1.0 200 OK
while 1: Connection: Close
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Content_type: text/html
data = raw_input(">>> ")
s.connect((machine, port))
s.send("t"+data+"\n") <HTML>
<PRE>
s.close() %s
</PRE>
if __name__ == "__main__": talk(sys.argv[1], eval(sys.argv[2])) </HTML>"""
Example Project: Web Site from Scratch Example Assignment: CGI Scripting
Goal: Create a complete functioning website using only CGI -- Common Gateway Interface
A text editor
An image editor
A Python interpreter HTTP Server Options
Configure global server (e.g. Apache)
Use Python CGIHTTPServer
Must Create Both Content and Server
Scripts are Just Programs
Python Provides TCP Server Framework
Input from env variables and stdin
Output to stdout
BTW: Python Also Has HTTP Server!
Python Provides
Standard module (cgi) to parse form input
Add-ons to produce nice HTML
Simple CGI Script Datbase Example: PostgreSQL
import cgi import pg # PostgreSQL database module
from pprint import pprint # pretty printing
RESPONSE="""Content-type: text/html
QUERY="""SELECT customer_name, balance
<HTML> FROM account, depositor
<HEAD> WHERE account.balance > 500
<TITLE>%s</TITLE> and account.account_number=depositer.account_number"""
</HEAD>
<PRE>
<BODY> db = pg.connect(dbname=’bank’, host=’localhost’, user=’zelle’)
%s res = db.query(QUERY)
</PRE> print res.ntuples()
</BODY>""" pprint(res.getresult())
pprint(res.dictresult())
form = cgi.FieldStorage() pprint(res.listfields())
content = []
for name in form.keys(): ----------------------------------------------------------------
content.append("Name: %s value: %s" % (name, form[name].value))
content.append("Done") 4
[(’Johnson’, 900.0), (’Jones’, 750.0), (’Lindsay’, 700.0)]
[{’customer_name’: ’Johnson’, ’balance’: 900.0},
print RESPONSE %("Form Echo", "\n".join(content)) {’customer_name’: ’Jones’, ’balance’: 750.0},
{’customer_name’: ’Lindsay’, ’balance’: 700.0}]
(’customer_name’, ’balance’)
Modules Available for Every Major DB OS Course is Perfect for Systems Language...
ODBC drivers IF you’re implementing an OS
MySQL
PostgreSQL
Commercial DBs (Oracle and friends) Python Excels for
Experimenting with system calls
Concurrent programming (processes and threads)
Pure Python DB: Gadfly
Simulations (queuing, paging, etc.)
Algorithm animations
Uses
Backend for web applications
Appropriateness Depends on Type of Course
Interactive query engine
DB Application Development
POSIX Process Calls Example Assignment: Process Sieve
# fork -- create a (duplicate) process
if os.fork() == 0: Implement Sieve of Eratosthenes using pipeline of
print "in child"
else:
print "in parent" processes
# exec -- overlay the process with another executable
os.execl("/bin/more", "more", "foo.txt") # note: no 0 terminator
os.execvp(sys.argv[0], sys.argv)
Each process filters out numbers divisible by its prime
# sleep -- put process to sleep for specified time
time.sleep(n)
Process pipeline grows as each prime is found
# exit -- terminate process
sys.exit(0)
def wait(self):
self.mutex.acquire()
self.count = self.count - 1
if self.count < 0:
wlock = thread.allocate_lock()
wlock.acquire()
self.queue.append(wlock)
self.mutex.release()
wlock.acquire() # suspend on new lock
else:
self.mutex.release()
def signal(self):
self.mutex.acquire()
self.count = self.count + 1
if self.count <= 0:
wlock = self.queue[0]
del self.queue[0]
wlock.release() # let the waiting thread go
self.mutex.release()
Student Project: Hungry Monkeys Python Resources
Textbooks (CS1, CS2)
"Python: How to Program," Deitel, Deitel, Liperi, Weidermann, andLiperi,
(Prentice Hall)