python.

RICE UNIVERSITY • COMP 140
A N E X P E R I M E N TA L TA L K F O R A N E X P E R I M E N TA L C O U R S E AUG 26 & 27, 2008

Daniel Sandler

dsandler@rice

http://www.cs.rice.edu/~dsandler/python/

1. 3.

2. 4.

1.
A young mind is corrupted.

Me, circa 2000

(very busy)

many languages C++ (work) OOP. popular Scheme (fun) pretty.Many tasks. powerful perl (utility belt) useful .

<> )]}\EsMsKsN0[lN*1lK[d2%Sa2/d0<X+d*lMLa^*lN%0]dsXx++lMlN/dsM0<J]dsJxp"|dc` . many languages C++ (work) OOP.`echo "16iII*o\U@{$/=$z. powerful unreadable by others perl (utility belt) useful unreadable by anyone print pack"C*".split/\D+/. popular painful development cycle Scheme (fun) pretty.Many tasks.pop.unpack"H*".[(pop.

a language I discovered then. called .

called .a language python! I discovered then.

.I am lazy.

Me. circa 2006 (lazy) .

Me. circa 2008 (aww!) (still lazy) .

I am lazy. • I am too lazy to wait for the compiler • I am too lazy to switch between programming languages all the time • I am too lazy to look up documentation • I am too lazy to try to decipher line noise .

Stuff I need to do: • Sketch new ideas quickly • Hack together analysis tools in the field • Turn prototypes into final research code • Build web applications for course & departmental use .

tell us about python already. Seriously. .2.

python is… • an interpreted programming language • object-oriented • dynamically typed • blah • blah • blah .

python is… • handy • smart • fun • helpful • pretty .

… image processing. concurrency • object serialization • cross-platform gui • sockets/smtp/mime/http/imap/xml/rpc/etc. . crypto. • other modules: databases. compression • regexps. everything I might need • data structures. • posix stuff.handy • built-in libraries. unicode • cgi/httpd scientific computing.

smart • python is not just a “scripting language” • pick your favorite programming paradigm • very fancy OOP not • functional programming: a just bd supported. but natural am l .

get an answer • the only calculator you’ll ever need • experiment with live objects • (no waiting for the compiler) .fun • every Python is an interactive workshop • the “read-eval-print loop” (REPL) • ask a question.

module is selfdocumenting • “Carry your documentation with you” functions to use in the REPL: help(foo) dir(foo) • Essential. function. class.helpful • Every object. don’t-leave-home-without-them • (It’s actually a property on the object) .

pretty public class Hello { public static void main(String[] args) { System. } } . world").out.println("Hello.

out.pretty public class Hello { public static void main(String[] args) { System. world"). } } .println("Hello.

x 2. math.sqrt(4*x). }x = Math. else: } } else{ .pretty (2) • Ever seen this? if (x ){ x: (x) { xx==2*x 2*x 2*x.2 } x = Math. else { while(x>0) { while x>0: while(x>0) x -=-= 2.sqrt(x) } .sqrt(x).

develop quickly • helpful: documentation is always there • pretty: ugly code is hard to write .The perfect date. indeed • handy: built-in libraries ftw • smart: a real programming language • fun: play around.

3. The (clean) Python phrasebook. .

Simple types • 1. 9999999999L • 'spam'. -2. '''multiline spam''' • True.5. 0xDA51D. "King Arthur's spam". 3+5j. False • None .

[2.Compound types • List (mutable sequence) • Dictionary (mutable hash table) • Tuple (immutable sequence) • ("eggs". True) • [1. 3]. 100. None. "eggs"] • {"eggs": "The finest eggs in all Lilliput" "spam": "Spiced ham from Camelot"} .

. "b": 2} •x+1 • y[1] • z["b"] # result is 2 # result is also 2 # . hey.Naming. this is a comment. 2.still 2 .. accessing • x = 1 # creates the name x and sets its value # to 1. Oh. 3] • z = {"a": 1. • y = ["eggs".

" % aDict ." % (whom. age) • "Hello %(name)s (%(age)d years old).String formatting • "Hello %s (%d years old).

conditionals def fib(n): """Recursively computes the nth Fibonacci number.Functions.""" if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) .

out.lang. long count = 0. i < line. if (!inword) { if (ch != ' ') { inword = true. } } } } } System.A simple program: “wc” import java. for (int i = 0.in)). } else { boolean inword = false.println(count). while (!done) { String line = input. boolean done = false.length().readLine().*. import java. if (line == null) { done = true. i++) { char ch = line. } } else { if (ch == ' ') { inword = false. public class wc { public static void main(String[] argv) throws IOException { BufferedReader input = new BufferedReader( new InputStreamReader(System. increment counter end word print . } } open file initialize read bail each char new word.*. count += 1.charAt(i).io.

readline() if line == '': # EOF done = True else: inword = False for char in line: if not inword: if not char.stdin.isspace(): inword = True count += 1 else: if char.“wc” in python (1) import sys done = False count = 0 while not done: line = sys.isspace(): inword = False print count read bail every char new word end word print .

readline() if line == '': # EOF done = True else: count += len(line.stdin.“wc” in python (2) import sys done = False count = 0 while not done: line = sys.split()) print count split string length of any sequence (default: into words) .

split()) print count iterate lines in a file .stdin: count += len(line.“wc” in python (3) import sys count = 0 for line in sys.

read().stdin.split()) read whole file into a string .“wc” in python (4) import sys print len(sys.

*. } } } } } System. } else { boolean inword = false. } } else { if (ch == ' ') { inword = false. } } .lang.io. count += 1. import java. boolean done = false. for (int i = 0.in)). i++) { char ch = line. while (!done) { String line = input. if (!inword) { if (ch != ' ') { inword = true.charAt(i).length(). i < line. long count = 0.println(count).out.the Java version import java. public class wc { public static void main(String[] argv) throws IOException { BufferedReader input = new BufferedReader( new InputStreamReader(System.readLine(). if (line == null) { done = true.*.

.4. Ride the snake.

NET CLR .Beyond the interpreter • Need speed? • Implement performance-critical code in C. wrap it in a Python interface for reuse • Missing call/cc? • Stuck in another runtime? • Stackless Python • Jython: Python syntax + JVM • IronPython: Python syntax + .

net/ • gnuplot.http://matplotlib.sf.Scientific computing • Numeric python .org/ • pylab/matplotlib .http://numpy.scipy.py. try python instead . pydot • Next time you reach for matlab or gnuplot.

End-user applications • GUI toolkits: • Tk • wxWidgets • MFC (Windows • Cocoa (OS X) • BitTorrent .

Industry • Indexing the known universe (Google) • Exploring the known universe (NASA) • Recreating the known universe (ILM) • Destroying the known universe (Eve Online) .

Education • Good for teaching • All the simplicity of Scheme • Familiar infix math • Widely used outside the academy • MIT intro curriculum has gone Python • And now…Rice’s new COMP 140 • A trend in CS education .

cs.org/ (updated 2006) • Programming Python (O’Reilly) • More links.rice.Further reading • Dive Into Python http://diveintopython.edu/~dsandler/python/ . plus these slides: http://www.

(my python story) 2. (resources) . (about the language) 3. (syntax) 4.1.

16 tonnes Brought to you by the Ministry of Silly Talks .