# Kim’s Python lesson

Saturday 1 December 2012This is almost 12 years old. Be careful.

I spent the afternoon on Thanksgiving teaching my 14-year-old niece Kim about programming in Python. She hadn’t done any programming before, but was very interested, so I figured we could just give it a shot. I didn’t have a text to follow, and hadn’t known she was interested, so I hadn’t prepared anything.

But the path we took seemed to work, so here’s what I remember of it, in rough outline form. As you look at the code samples, remember the goal here isn’t to use the best or most Pythonic way to write the code, but to use simple tools to teach beginning programming.

The text below is not for the teacher to read to the student, or for the student to read on their own. This is just a list of topics we discussed, and programs we wrote.

•    •    •

What is a computer program? Instructions for a computer to follow. Computers are really dumb, so you have to spell out everything precisely.

Install Python (IDLE doesn’t work well on a Mac, we ended up with plain-old textedit and a terminal.)

Try some arithmetic in the interactive prompt. Assign values to names:

`>>> 2 + 24>>> 10 * 3 + 5 * 345>>> x = 10>>> 2 * x20>>> x = x+1>>> x11>>> 2 * x22`

“x = 1” in Python is not like “x = 1” in algebra. You can’t say, “x + 1 = 2” in Python, and you can’t say “x = x + 1” in algebra.

Create and run a simple program:

`print "Hello, world!"`

You can ask for input from the user:

`name = raw_input("What's your name? ")print "Hi", name`

If statements let you make decisions:

`name = raw_input("What's your name? ")print "Hi", nameage = int(raw_input("How old are you? "))if age > 25:    print "Wow, you are old"`

An else clause lets you go either way:

`name = raw_input("What's your name? ")print "Hi", nameage = int(raw_input("How old are you? "))if age > 25:    print "Wow, you are old"else:    print "Don't worry, you're still cool"`

An elif clause lets you keep trying different conditions:

`name = raw_input("What's your name? ")print "Hi", nameage = int(raw_input("How old are you? "))if age > 25:    print "Wow, you are old"elif age < 6:    print "You're just a baby!"else:    print "Don't worry, you're still cool"`

We’ve used two kinds of values: numbers and text, called strings. You have to be clear which kind you have. 12 != “12”.

Loops: when you want to do something over and over, you can use a while loop. It checks a condition and if the condition is true, runs the statements, then checks the condition again etc, over and over, until the condition is false.

`count = 10while count > 0:    print "Count:", count    count = count - 1print "Blastoff!"`

Also, we can write “count = count - 1” as “count -= 1”

Play around with that first number. Computers can do a lot of boring stuff really quickly.

Let’s write a program to add up all the numbers up to 1000. You have to think like a computer, which means you can’t just say, “Add them all up,” you need to break it down into smaller steps.

`total = 0num = 0while num <= 1000:    total += num    num += 1print "total is", total`

Now let’s add a twist: let’s only include the number in the sum if the number is divisible by 3 or by 5. To see if a number is divisible by 3, you can test if N % 3 == 0. “%” gives you the remainder after dividing, and “==” is how you test for equality.

This program is where we start to get opportunities for real logic errors. If they happen, make sure you talk about them and how they happened before moving on.

`total = 0num = 0while num <= 1000:    if num % 3 == 0:        total += num    elif num % 5 == 0:        total += num    num += 1print "total is", total`

Try a new kind of value: lists. In the interactive prompt, try this:

`>>> nums = [1, 2, 3]>>> print nums[1, 2, 3]>>> print len(nums)3>>> nums.append(17)>>> print nums[1, 2, 3, 17]`

Lists can hold any kind of value, like text strings:

`>>> cats = ["penny", "kiki", "naomi"]>>> print cats['penny', 'kiki', 'naomi']>>> print len(cats)3>>> cats.append('arwen')>>> print cats['penny', 'kiki', 'naomi', 'arwen']`

Let’s write a program to catalog cats (Kim has 5 cats). It will ask the user for the name of a cat, and keep asking until the user types nothing, then will show how many cats the user has.

If you want to loop forever, or test a condition that you can’t test immediately, you can use “while True”. Remember while tests its condition and runs the loop if the condition is true. True is always true. Later, if you want to end the loop, you can use the “break” statement.

`cats = []while True:    name = raw_input("Tell me the name of a cat (just plain enter to end): ")    if name == "":        break    cats.append(name)print "You have", len(cats), "cats"`

Hmm, it looks kind of funny if you only have one cat, because it says, “You have 1 cats”. Fix that.

`cats = []while True:    name = raw_input("Tell me the name of a cat (just plain enter to end): ")    if name == "":        break    cats.append(name)if len(cats) == 1:    print "You have 1 cat"else:    print "You have", len(cats), "cats"`

or:

`# ...if len(cats) == 1:    group = "cat"else:    group = "cats"print "You have", len(cats), group`

We’ll add one more feature to our cat cataloguer: print the names of the cats. There’s another way to loop in Python beside “while”. A “for” loop will go around the loop once for each element in a list. We can use it to print the names of the cats:

`#.. tack this on the end of the cat cataloguer from above..print "Here are their names:"for cat in cats:    print cat`

Now we make a mighty leap to madlibs, which isn’t that much more complicated, but needs a few more new concepts.

Play in the interactive prompt with building a string by adding strings together:

`>>> s = "">>> s = s + "Hello">>> s += " world">>> print s'Hello world'>>> s += " I have something">>> s += " to say.">>> print s'Hello world I have something to say.'`

If we have a list of things, we can examine individual elements in the list:

`>>> cats = ["penny", "kiki", "naomi"]>>> print cats[0]'penny'>>> print cats[1]'kiki'>>> print cats[2]'naomi'`

To do madlibs, the story will be represented as a list of pieces, where each piece can be a literal piece of text in the story, or a slot to be filled in. A piece will be a 2-element list: for text, the first element will be ‘text’, and the second element will be the actual text to go in the story. For a slot, the first element will be ‘slot’, and the second element will be the prompt for the user. The madlib will be a list of these little lists:

`madlib = [    ['text', "Once upon a time there was a "],    ['slot', "an adjective"],    ['text', ", "],    ['slot', "another adjective"],    ['text', " "],    ['slot', "an animal"],    ['text', ". He liked to "],    ['slot', "a verb in the present tense"],    ['text', " all day. One day, he went to "],    ['slot', "an adjective"],    ['text', " "],    ['slot', "a place"],    ['text', " to meet "],    ['slot', "a person"],    ['text', "."],    ]`

When writing a madlib this way, it’s really hard to get the spacing and punctuation right...

The madlib program will scan the madlib. Each ‘text’ piece will be added to the story we’re building. For each ‘slot’ piece, we’ll prompt the user to give us something to go in the slot, and we’ll add their answer to the story. When it’s all done, we’ll print the story.

`madlib = [    #.. from above ..    ]story = ""for piece in madlib:    if piece[0] == 'text':        story += piece[1]    elif piece[0] == 'slot':        prompt = "Give me " + piece[1] + ": "        answer = raw_input(prompt)        story += answerprint story`

•    •    •

At this point, the student has a program they can actually enjoy. If all has gone well, they’ve probably wanted to show off each program to nearby admirers (typically parents), but the madlibs program is the crowning achievement.

By the way, the madlibs exercise is one I first did with my son Max when he was 13, and wrote about then, with more code and other ideas about how to expand it.

Working with Kim on this was really interesting. There were some parts where I was astonished that she understood so quickly, and then others where something she had understood in the previous program needed to be re-explained. Programming is a really foreign environment, and it’s hard for those of us who are fully steeped in it all day to realize just how foreign.

» 10 reactions

Ned - Great tutorial. Like the interactive nature of the program which makes it very interesting for a beginner. I think about giving this kind of programming tutorial for my elementary school children. Gave me some good ideas to try. Thanks
Interesting, thanks. I seem to enjoy reading about teaching children about the jobs we have ourselves: your post reminded me a bit of Katie Cunningham's post from a little while back. See http://therealkatie.net/blog/2012/oct/24/career-day/ (talking on school about your job)
Inspiring, thanks for sharing! I’m of a mind to try out some turtle demos with my niece.
Hi,
Thanks for sharing. Do you think it could have been interesting to talk about logics here:
```if num % 3 == 0 or num % 5 == 0:
total += num```
```if num % 3 == 0:
total += num
elif num % 5 == 0:
total += num```
@Grahack, yes we actually did a few versions of that problem, some dictated by bugs in Kim's code, some by tangents about variations in logic. In general, lots of these topics had tangents and discussions about options and so on. I kept this list more linear in the interest of space.
You're a good teacher, Ned. Kim's blessed to have you.

I'm wondering: Did you have Kim do everything herself or did you take the reins for parts?

Also, about how many hours would you say your programming session lasted?
@Kevin: mostly, Kim was doing the typing, but we talked a lot while she did. I tried also to say, "OK, great, now try it," even when I knew it wouldn't run, because it's important to get over the fear of experimentation. When we got to madlibs, I put the basic structure in place, partly because it was trickier, and partly because dinner was almost ready!

We probably spent about 2-3 hours total on all this, though it was spread over three different sittings. I was surprised she kept coming back, but I made clear that I was up for it if she was!
That's great, Ned, thanks! Student-motivated learning is a wonderful thing. Such home schooling seems to be growing and I'd love to see it overtake homogeneous mass education someday.
Ned, it was wonderful listening in on the session and trying out Kim's programs! Kim was working on something this weekend too- I will encourage her to get in touch and hopefully continue learning. Thanks.
Two powerful metaphors for explaining python programming to my ten year old daughter were:
The bit of the left of the equals sign is the labelled box (or collectionOf[labelled] boxes) that the stuff on the right is stored in.
Objects are explained by HeyYou.DoThis(withthis, andthis)
This was towards to analysis for Science Fair, so there was a concrete project she was working towards.