Download Dondero Python summary

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Princeton University
COS 333: Advanced Programming Techniques
A Subset of Python
Program Structure
#!/usr/bin/env python
# Print "hello world" to stdout.
print 'hello, world'
----------------------------------------------------------------------------------#!/usr/bin/env python
# Print "hello world" to stdout.
def f():
print 'hello, world'
if __name__ == '__main__':
f()
----------------------------------------------------------------------------------#!/usr/bin/env python
def sqr(i):
return i * i
def main():
print sqr(5)
if __name__ == '__main__':
main()
----------------------------------------------------------------------------------Interpreter must see definition of function before top-level call of function.
Typically a module must import names from other modules
import module
# Makes module namespace available within this module.
from module import name # Adds name from module into this module's namespace.
Building and Running
python module.py
----------------------------------------------------------------------------------chmod 700 module.py
module.py
----------------------------------------------------------------------------------python
import module.py
Terminal I/O
Page 1 of 7
Reading from stdin:
str = raw_input()
str = raw_input(promptstr)
from sys import stdin
str = stdin.readline()
Writing to stdout:
print str
Writing to stderr:
from sys import stderr
stderr.write(str)
Keywords
and, assert, break, class, continue, def, del, elif, else, except, exec, finally,
for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return,
try, while, with yield
Primitive Data Types
Integer:
Floating point number:
String:
Boolean:
Null object:
1, 12345, 01, 012345, 0x1, 0x1DB5 (no theoretical size limit)
0.0, 1.23, 1.23e4
'hi', "hi"
True, False
None
A datum of a primitive type is an object.
Conversions: int(obj), float(obj), str(obj), bool(obj)
Type checking: isinstance(obj, class)
No declaration statements; variables are created when first assigned a value
del(obj) deletes obj
Operators
{key:expr,...}
[expr,...]
(expr,...)
f(expr,...)
x[startindex:stopindex]
x[index]
x.attr
x**y
~x
+x, -x
x*y, x/y, x//y, x%y
x+y, x-y
x<<i, x>>i
x&y
x^y
x|y
x<y, x<=y, x>y, x>=y
(1) dictionary creation
(2) list creation
(3) tuple creation or just parentheses
(4) function call
(5) slicing (for sequences)
(6) indexing (for containers)
(7) attribute reference
(8) exponentiation
(9) bitwise NOT
(10) unary plus, unary minus
(11) mult, div, truncating div, remainder
(12) addition, subtraction
(13) left-shift, right-shift
(14) bitwise AND
(15) bitwise XOR
(16) bitwise OR
(17) relational
Page 2 of 7
x!=y, x==y
x is y, x is not y
x in y, x not in y
not x
x and y
x or y
(17)
(18)
(19)
(20)
(21)
(22)
relational
identity tests
membership tests
logical NOT
logical AND
logical OR
----------------------------------------------------------------------------------formatstr % tuple
string formatting (formatstr as in C)
'%d plus %f is %f' % (i, x, i+x)
Statements
Assignment:
var=expr, var+=expr, var-=expr,
var*=expr, var/=expr, var//=expr, var%=expr, var**=expr,
var&=expr, var|=expr, var^=expr, var>>=expr, var<<=expr
del(var) deletes var
Unpacking assignment:
var1,var2,... = iterable
No-op:
pass
Assert:
assert expr, message
Print:
print expr,...
print expr,...,
← hack
Function call:
f(expr, name=expr, ...)
Object references are passed by value
return as in C
Selection:
if expr:
statements
elif expr:
statements
else:
statements
Note: False, 0, None, '', "", [], (), and {} all indicate logical FALSE; any other value indicates logical TRUE
Iteration:
while expr:
statements
Note: False, 0, None, '', "", [], (), and {} all indicate logical FALSE; any other value indicates logical TRUE
for var in range(startint, stopint):
Page 3 of 7
statements
for var in range(stopint):
statements
for var in iterable:
statements
for key,value in mapping.iteritems():
statements
break as in C
continue as in C
Exception handling:
try:
statements
except ExceptionType, e:
statements
raise ExceptionType(str)
Indentation matters!!!
Classes, Objects, and Object References
All fields and methods are public.
By convention, consider fields and methods with leading underscore to be private.
#!/usr/bin/env python
class MyClass (object):
def __init__(self, i):
self._i = i
def get(self):
return self._i
def set(self, i):
self._i = i
def __str__(self):
return str(self._i)
def __eq__(self, other):
return self._i == other._i
def __ne__(self, other):
return self._i != other._i
def __hash__(self):
return hash(self._i)
# weak
if __name__ == '__main__':
myObj1 = MyClass(5)
print myObj1._i
myObj1.set(10)
print myObj1.get()
print str(myObj1)
print myObj1
myObj2 = MyClass(10)
# No privacy!!!
# calls myObj1.__str__()
# calls myObj1.__str__()
Page 4 of 7
if (myObj1 == myObj2):
print 'equal'
if (myObj1 != myObj2):
print 'not equal'
dict = {myObj1:myObj2}
# calls myObj1.__eq__(myObj2)
# calls myObj1.__ne__(myObj2)
# calls myObj1.__hash__()
del(myObj2)
del(myObj1)
Data Structures
All are objects defined in a standard library.
Iterable
Container
Mapping
Dictionary
Sequence
String
Tuple
List
Set
File
----------------------------------------------------------------------------------String (immutable, hashable)
str = 'hi'
str = "hi"
str = r'hi' # raw string; backslashes not interpreted
Tuple (immutable, hashable)
tuple = (obj1, obj2, ...)
tuple = (obj1, )
← hack
List (mutable, not hashable)
list = [obj1, obj2, ...]
Set (mutable, not hashable)
set = set(list1)
Dictionary (mutable, not hashable; keys must be hashable)
dict = {keyobj1:valueobj1, keyobj2:valueobj2, ...}
File
file = open('filename', mode='somemode')
somemode: r, w, a, r+, w+, a+ (as in C)
----------------------------------------------------------------------------------Nonmutating Operator on Iterables
bool = obj in iterable
# bool = iterable.__contains__(obj)
Nonmutating Function on Containers
i = len(container)
# i = container.__len__()
Page 5 of 7
Nonmutating Operators/Methods on Sequences
seq1 = seq2 + seq3
# seq1 = seq2.__add__(seq3)
obj = seq1[i]
# obj = seq1.__getitem__(i)
seq1 = seq2[i:j]
# seq1 = seq2.__getitem__(slice(i,j))
i = seq1.count(obj)
i = seq1.index(obj)
The string class has many more methods. Some useful ones: count, endswith, find, index, isalnum, isalpha, isdigit,
islower, isspace, isupper, join, lower, lstrip, replace, rfind, rstrip, split, startswith, strip, upper.
Mutating Operators/Functions/Methods on Sequences
seq[i] = obj
# seq.__setitem__(i, obj)
seq1[i:j] = seq2
# seq1.__setitem__(slice(i,j), seq2)
del(seq[i])
# seq.__delitem__(i)
del(seq[i:j])
# seq.__delitem__(slice(i,j))
seq1 += seq2
# seq1.__iadd__(seq2)
seq.append(obj)
seq.extend(iterable)
seq.insert(index, obj)
seq.remove(obj)
obj = seq.pop()
obj = seq.pop(index)
seq.reverse()
seq.sort()
seq.sort(fun)
Nonmutating Methods on Sets
set1 = set2.copy()
set1 = set2.difference(set3)
set1 = set2.intersection(set3)
bool = set1.issubset(set2)
bool = set1.issuperset(set2)
set1 = set2.symmetric_difference(set3)
set1 = set2.union(set3)
Mutating Methods on Sets
set1.add(set2)
set.clear()
set.discard(obj)
obj = set1.pop()
set.remove(obj)
Nonmutating Methods on Mappings
map1 = map2.copy()
bool = map.has_key(obj)
list = map.items()
list = map.keys()
list = map.values()
iterable = map.iteritems()
iterable = map.iterkeys()
iterable = map.itervalues()
obj = map1.get(key)
obj = map1.get(key,default)
Mutating Methods on Mappings
map.clear()
map1.update(map2)
Page 6 of 7
map.setdefault(key)
map.setdefault(key,defaultObj)
obj = map.pop(key)
obj = map.pop(key, defaultObj)
obj = map.popitem()
Methods on Files
str = file.readline()
list = file.readlines()
print >>file, str
file.write(str)
file.writelines(list)
file.close()
# necessary to avoid truncation
Command-Line Arguments
sys.argv is a list
sys.argv[0] is the name of the program
sys.argv[1:] are command-line arguments
from sys import argv
from sys import exit
from sys import stderr
...
if len(argv) != 3:
print >>stderr, 'Usage:', argv[0], 'arg1 arg2'
exit(1)
Debugging
To use the pdb debugger:
python -m pdb module.py
Debugger commands:
help
break functionOrMethod
break filename:linenum
run
list
next
step
continue
print expr
where
quit
Common commands have abbreviations: h, b r, l, n, s, c, p, w, q
Blank line means repeat the same command.
Etc.
We'll cover other features of Python throughout the course as necessary.
Copyright © 2011 by Robert M. Dondero, Jr.
Page 7 of 7