jump to navigation

Teaching Programming With Python January 7, 2011

Posted by PythonGuy in Advanced Python, Beginning Programming, Mako, Python.
add a comment

Python Guy taught Python Guy Jr. (9 years old) about Boolean Algebra. (It’s really easy because there are only two numbers, and so you have a 50% chance of getting any problem right by guessing. I guess that’s why they don’t teach it in Kindergarten, although if we did, I think a lot of kids would learn to like math a lot more.)

Python Guy popped open python on the konsole in KDE on Fedora 13. Although this box doesn’t have Flash installed (on purpose), it is, to Python Guy’s spawnlings, the magic box that does things that blow their mind every day before they even wake up late for school.

Python Guy watched the Python Guy Jr. learn all about short-circuiting. When Python Guy was a young one, practicing on the Commodore 64 (or was it Borland C several years later?), I remember the thing I constantly awed over was the short-circuit operators, “and” and “or” in Python, but && and || in C.

Ah, the magic!


>>> 7 and 4
4
>>> 0 and 5
0
>>> 7 or 8
7
>>> 0 or 10
10

Of course, when you understand what is happening, you are tempted to do fancy things like this in Mako:


You have bought <% n %> <% n == 1 and "item" or "items" %>.

Until you mess up, that is, and foolishly choose something false for the positive case:


You have bought <% n %> item<% n == 1 and "" or "s" %>.

(Can you spot it? Neither can I when I do it.)

So Python has the infamous and hotly debated “a if b else c” expression, which does the right thing:


You have bought <% n %> <% "item" if n == 1 else "items" %>.

But is that really the right thing? No, it’s not. If you want to do plurals, you need to be really, really smart about it. Even if you have a library that will pluralize your English nouns, you’ve got to think of the Germans, Slovenians, and Japanese who might not like ordering their stuff in English.

Back to the original topic, Boolean Algebra is a great way to teach Algebra and a great way to play with some of the most advanced features of Python. It’s almost magical how it all works, at least in the imagination of a 9-year-old.

Advertisements