I ran a post-mortem for this term's run of the Software Carpentry course on Monday. Students gave me a lot of useful feedback, which I'll post as soon as I find my notes ;-). One comment that's got me thinking was about the way sample programs are presented in the notes. Right now, I include the finished code in a monochrome fixed-width font. Adding syntax highlighting won't be difficult; the more interesting suggestion was to write the code "live", while talking aloud. The main benefit would be that it would prevent the instructor from racing by something that students need time to absorb. It would also force (or at least encourage) the instructor to think aloud about what the code was doing, how it was structured, etc.
The problem is that I want the notes to be usable on their own, without an instructor, both on-line and when printed. That suggests some Powerpoint-style animation trickery to reveal successively larger versions of the code sample one after the other, accompanied by comments. I'm envisioning something like this:

Invert a dictionary without losing any data.

1

2

3

becoming this:

def invert(d):

result = {}

...invert d into result...

return result

Step 1: signature and skeleton.

1

2

3

then this:

def invert(d):

result = {}

for (k, v) in d.items():

result[v] = result.get(v, []).append(k)

return result

Step 2: use a list for values, so that collisions aren't fatal.

1

2

3

and then this:

def invert(d):

'''Invert a dictionary, keeping colliders.'''

result = {}

for (k, v) in d.items():

result[v] = result.get(v, []).append(k)

return result

Step 3: remember, always document your code.

1

2

3

My questions are:

Is there a better way to do this?

If not, is there a tool out there (presumably written in JavaScript) that'll do this?

If so, what happens in the print version? I'd rather not display the same lines of code several times---some kind of callout or highlighting would be best---but I want to be able to do everything from a single source representation.

Answers to me, please; best response wins an all-expenses-paid trip to the nearest Tim Horton's.