Introduction To Python
Introduction To Python
Why Python?
• interactive "shell"
• basic types: numbers, strings
• container types: lists, dictionaries, tuples
• variables
• control structures
• functions & procedures
• classes & instances
• modules & packages
• exceptions
• files & standard library
• what's new in Python 2.0 and beyond
Try It Out!
• Lookup:
• d["duck"] -> "eend"
• d["back"] # raises KeyError exception
• Presence check:
• d.has_key("duck") -> 1; d.has_key("spam") -> 0
– no restrictions on values
• Keys will be listed in arbitrary order
– again, because of hashing
Tuples
• No need to declare
• Need to assign (initialize)
• use of uninitialized variable raises exception
• Not typed
if friendly: greeting = "hello world"
else: greeting = 12**2
print greeting
• Everything is a "variable":
• Even functions, classes, modules
Reference Semantics
a = [1, 2, a 1 2 3
3]
a
b=a 1 2 3
b
a
a.append(4 1 2 3 4
) b
Changing an Integer
a=1 a 1
a
b=a 1
new int object
b created
by add operator
(1+1)
a 2
a = a+1 old reference deleted
by assignment (a=...)
b 1
Control Structures
break
continue
Grouping Indentation
In Python: In C: Bingo!
---
---
---
3
---
for i in range(20): for (i = 0; i < 20; i++) ---
---
if i%3 == 0: { 6
---
---
if (i%3 == 0) { ---
print i 9
---
printf("%d\n", i); ---
if i%5 == 0: ---
if (i%5 == 0) { 12
print "Bingo!" ---
---
---
print "---" printf("Bingo!\n"); } 15
Bingo!
---
} ---
---
18
printf("---\n"); ---
---
}
Functions, Procedures
>>> gcd.__doc__
'greatest common divisor'
>>> gcd(12, 20)
4
Classes
class name:
"documentation"
statements
-or-
class name(base1, base2, ...):
...
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
...
May also be class variable assignments
Example Class
class Stack:
"A well-known data structure…"
def __init__(self): # constructor
self.items = []
def push(self, x):
self.items.append(x) # the sky is the limit
def pop(self):
x = self.items[-1] # what happens if it’s empty?
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 # Boolean result
Using Classes
class FancyStack(Stack):
"stack with added ability to inspect inferior stack items"
class LimitedStack(FancyStack):
"fancy stack with limit on stack size"
class Connection:
verbose = 0 # class variable
def __init__(self, host):
self.host = host # instance variable
def debug(self, v):
self.verbose = v # make instance variable!
def connect(self):
if self.verbose: # class or instance variable?
print "connecting to", self.host
Instance Variable Rules
def foo(x):
return 1/x
def bar(x):
try:
print foo(x)
except ZeroDivisionError, message:
print "Can’t divide by zero:", message
bar(0)
Try-finally: Cleanup
f = open(file)
try:
process_file(f)
finally:
f.close() # always executed
print "OK" # executed on success only
Raising Exceptions
• raise IndexError
• raise IndexError("k out of range")
• raise IndexError, "k out of range"
• try:
something
except: # catch everything
print "Oops"
raise # reraise
More on Exceptions
• User-defined exceptions
– subclass Exception or any other standard exception
• Old Python: exceptions can be strings
– WATCH OUT: compared by object identity, not ==
• Last caught exception info:
– sys.exc_info() == (exc_type, exc_value, exc_traceback)
• Core:
– os, sys, string, getopt, StringIO, struct, pickle, ...
• Regular expressions:
– re module; Perl-5 style patterns and matching rules
• Internet:
– socket, rfc822, httplib, htmllib, ftplib, smtplib, ...
• Miscellaneous:
– pdb (debugger), profile+pstats
– Tkinter (Tcl/Tk interface), audio, *dbm, ...
Python 2.0: What's New
• Augmented assignment: x += y
• List comprehensions:
[s.strip() for s in f.readlines()]
• Extended print: print >>sys.stderr, "Hello!"
• Extended import: import foo as bar
• Unicode strings: u"\u1234"
• New re implementation (faster, Unicode)
• Collection of cyclic garbage
• XML, distutils
Python 2.1: What's New
• Type/class unification
– class mydict(dict): …
• Fix division operator so 1/2 == 0.5; 1//2 == 0
– Requires __future__ statement in Python 2.x
– Change will be permanent in Python 3.0
URLs
• http://www.python.org
– official site
• http://starship.python.net
– Community
• http://www.python.org/psa/bookstore/
– (alias for http://www.amk.ca/bookstore/)
– Python Bookstore
Further Reading