Python in 90 Minutes (Or your money back) ((Note: Python is free)) 10 Mar 2006 - Dan Sandler ---------------------------------------------------------------------- Introduction - Java is not the only game in town - C# being used in MS shops and for Windows development - C++ still going strong in large apps - C is still the language of choice for low-level hacking - The "scripting languages" - The glue of the internet - Perl (enormous, disgusting hack; extremely useful, but essentially end-of-life) - PHP (very popular for Web scripts) - Python (often used for glue, but surprisingly powerful, and can be used for large applications, with excellent results---ever hear of something called BitTorrent?) - Ruby (even more juicy PL cleverness than Python) - We should also talk a little about general-purpose languages vs. domain-specific languages - DSLs are kind of a trend, because people realize that the expressivity of the language ought to be strongly influenced by what you're trying to say - GPPLs: - The Algol-deriveds (Pascal, C, Java) - LISP/Scheme - FORTRAN - DSLs: - MATLAB (built-in FFT function) - Your ADVENTURE world definition file - Your ADVENTURE command parser - Embedded GPPLs that look like DSLs: - the GIMP (scheme) - Flash (ActionScript) - Tcl - Today we'll talk mostly about Python - Why? If I keep hopping back and forth you won't remember any syntax - We might have talked about Ruby, if I were personally more comfortable with it - What is Python? It's a GPPL that has some great expressivity, is fun to program in, and, by the way, has a huge built-in library with lots of useful stuff in it - Never heard of it? (Heard of BitTorrent?) Linguistic expressivity (LESS TYPING) - chatting with the interpreter * Every Python is a DrPython * The only calculator you'll ever need * Code-Compile-Run-Loop = read, guess, crash, hate * REPL = poke, sketch, experiment, love - basic syntax * What's the first program you write? (What's the first program you wrote in this class?) - What did your Java version look like? public class Hello { public static void main(String[] args) { System.out.println("Hello, world"); } } - Python print "Hello, world" - can be fed to the terp, or placed in hello.py and run at cmdline * Scalar data - numbers - infix math (sorry, Scheme) - strings - operators - contrast with Java's .equals() for strings - if you really want that, that's what "is" is for - your first function call: len(str) - actually your second---print was a hidden function call - tuples - lists How would I make a list of the first six nonnegative integers in Java? [0,1,2,3,4,5] range(5) => [0,1,2,3,4,5] .reverse() .sort() [x] [x:y] - dictionaries - String formatting: - finally Java 1.5 added printf() to PrintStream System.out.printf("Hello %s (age %d), how are you?", whom, age); - But how about formatting to an arbitrary string? - Python: any string supports the % binary operator "Hello %s (age %d), how are you?" % (whom, age) * Variables - assignment - swapping without a temporary? * Builtins - infix math (sorry, Scheme) - len() * Types type(1) type('1') int('1') str(1) * Functions def helloworld(): print "hello world" def hellosomeone(whom): print "hello " + whom def hellosomeone(whom): print "hello, " + whom + ", it's nice to meet you" * Classes and objects The hello-world class class HelloWorld: def __init__(self, whom): self._whom = whom def hello(self): print "Hello, %s!" % self._whom - useful libraries * Super-basic: Files * Basic: re - A simple program: wc - How long was your Java version? - What did it look like? # wc.py (version 1) import sys done = False count = 0 while not done: line = sys.stdin.readline() if line == '': # EOF done = True else: inword = False for char in line: if inword: if char.isspace(): inword = False else: if not char.isspace(): inword = True count += 1 print count # wc.py (version 2) import sys done = False count = 0 while not done: line = sys.stdin.readline() if line == '': # EOF done = True else: words = line.split() for word in words: count += 1 print count # wc.py (version 3) import sys done = False count = 0 while not done: line = sys.stdin.readline() if line == '': # EOF done = True else: count += len(line.split()) print count # wc.py (version 4) import sys count = 0 for line in sys.stdin: count += len(line.split()) print count # wc.py (version 5) import sys print len(sys.stdin.read().split()) Libraries - Python's motto: "batteries included" * basic: sys - sys.stdout * os.* - Java doesn't really like playing with the OS. Python does. * Useful: time, smtplib, urllib * Bad memories: zlib, gzip - simple program: webget # webget.py import sys import urllib url = sys.argv[1] outname = sys.argv[2] page = urllib.urlopen(url) outfile = open(outname, 'w') for line in page: outfile.write(line) page.close() outfile.close() - simple class: stopwatch # stopwatch.py import time class Stopwatch: def __init__(self): self.reset() def reset(self): self._start = None self._stop = None def start(self): self._stop = None self._start = time.time() # now! def elapsed(self): if self._start is None: return 0 elif self._stop is None: end = time.time() else: end = self._stop return end - self._start def state(self): if self._stop is None and self._start is not None: return "RUNNING" else: return "STOPPED" def look(self): return "elapsed time: %.2f sec (%s)" % (self.elapsed(), self.state()) def stop(self): self._stop = time.time() - keyword, optional arguments (BC #3) - Revenge of FuncProg * lambda (vs. anonymous classes) * list comprehensions (vs. for loops) GUI - Tk - Wait, didn't we already talk about Tcl? - They're closely related, but Tk is a GUI toolkit, and Tcl is the DSL that glues it together - It was originally designed to be used in C, with Tcl here and there to help patch it up - Tcl was powerful enough that people wrote whole programs in it for a while - Tkinter comes with every Python, so let's use that - More modern GUI toolkits: - wxWidgets (many programming languages) - Cocoa (OS X only) - Swing (!?!?!) - Example session from Tkinter import * hello = Button(text="Hello") hello.pack() world = Button(text="World") world.pack() hello.config(text="Bonjour") world.config(text="Monde") hello.config(font="Times 24 italic") world.config(font="Lucida\ Handwriting 50") hello.pack(side="left") world.pack(side="right") hello.pack(side="left", fill="both") world.pack(side="right", fill="both") world.pack(side="right", fill="both", expand=1) Isn't this more fun than guessing at the way Swing will lay things out? # vim: ts=4 sts=2 sw=2 et: