Archive for Python

Coding with youngsters using pgzero on RPi: Part I

An eager young coder on Step 3

Some of you will know that several-times pyweek winner Daniel Pope has put together a simple framework called pgzero to sit on top of pygame. It’s Python 3 only and is especially aimed at educational use, and we spent the last London Python Dojo coming up with examples which used it.

Its main selling point is that it supplies behind the scenes some of the boilerplate code you’d otherwise have to write to get pygame up and running in a game loop. The simplest valid pgzero game is an empty .py file! From this, pgzero will produce a blank window of the default size, which will exit if you press Ctrl-Q. Adding a few “magic” constants will get you a window of a certain width & height, with a title and its own icon. After that, just define draw() and update() and add on_<event> handlers. And you have the makings of a game. There’s a built-in Actor class which essentially acts as a sprite, and easy-to-use image & sound loading. Plus some other goodies we didn’t use.

My team was responsible for the Breakout clone at the Dojo and I took it away and demonstrated it at the next evening’s Twickenham Coding evening, a friendly meetup in a room over a pub attended by teachers, code club leaders and educators. Altho’ we’d developed on my Windows laptop, I’d already planned to use the Raspberry Pi, about which more later, and I was very pleased when it ran on the Pi without a glitch at the Twickenham meetup. The message from the teachers I showed it to (mostly at the upper-Primary range) was: still too much code. But I got some useful feedback and set to work to adapt it.

My plan was to use pgzero and the Breakout game as the basis for a short series of workshops at the boys’ club I help to run in west London. But the lads aren’t into coding as such, and I knew from past experience that they could easily lose heart and get distracted if they didn’t instantaneously produce a Call of Duty lookalike. So I aimed for two things: cutting down the code complexity so there were as few concepts as possible to get across; and breaking it up into chunks which I could present one at a time, each building on the code from the previous chunk.

The result, for the impatient, is in the piece-by-piece branch. But first, there are some yaks we need to shave.

The setup


I was keen to use the Raspberry Pi for this.

  1. It’s cheap and so the club can afford to buy several of them; and one or two of the lads have their own
  2. It’s quite different from the (often literally) black box computers they’ll generally use so they don’t immediately see it as a mere entertainment source (ie they’re more likely to enter into a spirit of producing rather than only consuming)
  3. In later sessions I hope to introduce some simple electronics via the CamJam EduKit and similar things where the RPi excels
  4. It’s a Raspberry Pi! Everyone’s talking about them. Parents are keen on them. It creates a buzz around the activity which would be lacking if I’d used some other, equally capable, platform

We already had one RPi, an original Model B; someone tweeted that RS had Model B+ going at £16 each which is well within the budget I’d set for a couple more. Fortunately we have a number of monitors (VGA), which would otherwise have been beyond us to buy. The excellent PiHut also had the necessary accoutrements at affordable prices.

As everything was taking place in our club building, which isn’t networked, I used a spare laptop setup with lubuntu to run dnsmasq for a very easy local DHCP / DNS solution. The Pis were all wired to a simple 10/100 switch.

Expecting about 6 people, I’d planned to run in a classroom mode, with my laptop able to view individual screens if anyone needed help. I’d also thought of having my screen “broadcast” to theirs. I was a little surprised that there doesn’t seem to be a definitive way of doing this. iTalc2 looked promising, but needed a fair bit of setup. There are several commercial solutions, so presumably schools are able to budget for this kind of thing. In the end, I installed x11vnc on each of the RPis. But with only 4 boys in the end, and another tech-savvy leader, it was more sensible to physically wander around to help. I do plan to look into the reverse: broadcasting my screen. We don’t have any kind of projector at the moment, and in any case I’ve never found that a satisfactory solution for showing code.

The Software

The focus of the first sessions was the use of pgzero to produce the simple Breakout clone mentioned above. But first I had to bring the complexity of the code right down, taking advantage of the fact that pgzero hides away some of the messier boilerplate. These were first-time programmers and I would be throwing a lot of new concepts at them in a fairly short space of time. (Fortunately they’re all in Years 8 to 10 at school so I didn’t have to explain too much about coordinate systems and vectors).

Responding to an issue on the pgzero tracker, I’ve submitted a PR for a pure Python implementation of the pygame Rect class. The ostensible need was to allow for floating-point size and position changes. But a secondary effect, of more immediate use to me, was the possibility of adding arbitrary attributes to a Rect instance, such as colour and direction.

So the boys were working off my fork of the pgzero repo, installed via “pip install -e .” to track the development version. They were also unwittingly working off the piece-by-piece branch of my fork of the breakout code, although I was feeding it to them a piece at a time. I’d made use of the pgzero Rect to be able to add colour and direction as attributes, which did away with the awkward global variables of the original codebase. The result, though I say it myself, is about as stripped back as you can get while still actually doing something. The global blocks setup is a little clumsy, but the alternatives I tried were no better.

The Workshop

I’d set up our own Raspberry Pis and for the one lad who brought his own I did the necessary config while they were playing football outside. I persauded them all to close down Minecraft (”Look! It’s got Minecraft!”) and Mathematica (it’s got a shiny red icon, just asking to be pressed…).

I got them all to open a terminal window and cd to ~/work/breakout where I’d cloned and then started a new branch with no files. They ran IDLE3 and started a new file called “” (or “” or “” depending on the skill of the typist). I got them to run pgzrun against their new file and use Ctrl-Q to exit the resulting window. So far, so good.

From this point on, I fed them one step at a time on paper from the piece-by-piece branch. I’d considered other options: projecting the code, having them “git checkout” to the right tag, even reading it out or live-coding it myself. But this seemed the most trouble-free option and, basically, it worked.

After they’d got each update working, I highlighted a few new or repeated features. (”That’s a name; you defined that earlier”, “That’s a function; you run all that code in one go by using the function name”) etc. One of our other club leaders, Albert, is also a professional coder (PHP) and was very able to help so between us we kept the pace going despite the variations in typing ability.

At the end of the first session they’d reached step 6 out of 12.


What worked?

  • The pacing was basically about right. One of the steps had a little too much code in it, but I needed to have a change of some sort at the end of each step, and there really wasn’t anything I could do about it
  • I was very pleased the way in which the boys worked out the obvious typing bugs; they very quickly spotted when uppercase/lowercase was wrong or when they’d misspelt a name. I very rarely had to point out anything obvious.
  • Step 4 (when the bat responds to the on-mouse-move event) was the winner. Simple as it was, the boys loved the interaction. When someone got it slightly wrong (bat.centrex = y) causing the bat to move horizontally as the mouse moved vertically, they all wanted to try it. When I suggested they swap both coordinates (bat.centrey = x; bat.centrex =y) they’d have stayed there for ages.
  • I encouraged them to change things (the screen size, the colours etc.) and I was pleased that one lad, after I’d explained how names work, changed his “bat” and “ball” names to something else — altho’ this caused problems later when I was helping him debug as I couldn’t tell which object was which!
  • Although I’d had planned for a two-hour session, the 90 minutes we ended up with was about right

What didn’t work?

  • I should have brought step 4 in a little earlier, perhaps creating the bat before the ball and then letting it move
  • Several times I had to draw things up on the whiteboard to illustrate the coordinate system etc. This probably would have worked better with a screen broadcast from an IDLE session.
  • I had intended to have them try things out in IDLE, starting from a “from pgzero.builtins import *”. This didn’t really happen, although I did get them to do some experiments with the modulo operator when explaining the colour looping for the blocks.


Overall, I was very happy with the way it worked. I had four non-programmers dive in and basically enjoy themselves. I’m hoping to use the next session to finish the game and get them to play around with bells-and-whistles (make it go faster, have a bat on each side-wall etc.). After that I hope to connect up some simple LED / buzzers to react to the game.

FWIW I’d love to do a networked version where the ball disappears off one screen and appears on the next. Each person’s ball could be colour-coded and a ball will only destroy blocks of its own colour, so you have to use balls from your neighbour’s games to finish your own. Or something. I love the idea of the social aspect that would introduce, as well as the fact that someone could have two or even more balls in play on their own screen.

re RPi Launch Day post-mortem

There’s an article over on the Raspberry Pi blog which does a very competent job of writing up the actions & reactions necessary to manage their website when the announcement of the Model 2 went live.

I love these sort of post-mortem articles when they’re written by competent professionals (as opposed to clueless PR agents). I enjoyed reading the writeups on the PyCon networking even though an amount of it was beyond me as I’m not a network specialist.

What’s most interesting about the RPi writeup, though, is the author’s responses to the (presumably) well-meaning suggestions for how to improve things. I love how he points out with one suggestion after another that their existing solution is essentially doing what the commenter is proposing, only perhaps without the buzzword attached. Finally, he cracks a little, and plays the Mongo is Webscale card (which I’d forgotten all about).

Go and have a look; it’s a fun read!

Raspberry Pi-themed Dojo at BAML

Yesterday Bank of America once again hosted the London Python Code Dojo, this time at their St Paul’s offices. I don’t know what the normal use is for the room we were in, but it felt like a cross between a banqueting hall and something from Khazad-dûm. Very grand and with nice AV facilities: one big screen, several smaller screens and microphones. As is customary, the hosts provided beer & pizza, but as usual with BAML, in a somewhat classier mode, with slices and plates and a variety of drinks served by staff. All very much appreciated.

They’d also done all the setup, so we had 8 or 10 Raspberry Pi rigs with screens and enough keyboards and so on to go round. The networking took some doing and ended up being a cat’s cradle of very long ethernet cables all routing — I understand — through one all-the-data-you-can-eat phone connection! Which worked fine.

Al Broomhead and Tina Zhang gave a joint lightning talk on a couple of projects they’d been involved in on a recent Hack Day. Ben Nuttall from the Raspberry Pi Foundation had been good enough to come and join us and gave an overview of some of the resources they already have to help people use the RPi and to encourage any contributions the evening might bring forth.

Slightly differently from our usual approach, we had several different projects going during the evening. The idea was to come up with something which showcased the Raspberry Pi in some way. In the end, we had: a very simple approach to a door-challenge mechanism; a on-screen 7-segment display; an automated light which reacted to the hue of a chosen image; a text-adventure interface to Minecraft (”go forward; dig 5″); a morse-code reader using a Pibrella; and a couple of things which I’ve forgotten (sorry; someone ping me a reminder…).

At the end, of course, we had a name-draw for the book donated as usual by O’Reilly. And thanks go to BAML for their continued sponsorship of the Dojo. And to the BAML guys (and I think it was all guys) in particular for all the prep and tidy-up work to get the kit in place for us.

It was nice to see new people as well as the familiar faces. If anyone who was there wants to contribute their code or ideas to the Raspberry Pi Foundation, get in touch with Ben Nuttall. You can see a few photos via the @ldnpydojo twitter account. If any more show up we’ll try to retweet them.

London Python Dojo December 2014

I feel like a sub-editor just struggling really hard to avoid punny headlines like “A Unique Experience” and “5 Unique Solutions” and so on… because last night’s challenge was to recreate the Unix “uniq” command in Python. In fact, this was chosen only after a tie in the first round of voting giving us a top 4 rather than a top 3 and a triple-tie for second place in the second round, although with one clear winner. (Otherwise I was going to have to move onto a Single Transferrable Vote round).

It was nice to see quite a few new faces, 6 or so first-timers and several who haven’t been for a while or who have been only once or twice. Plus, of course, the old familiar faces. Fry IT continue to host us generously, including ordering artisan pizzas with enormous slices. And O’Reilly came across as always with a book for the giveaway at the end.

Most teams went for a fairly straight solution, one of them managing to carry a TDD approach pretty much throughout. One team had grander ambitions for field selection and datatype conversion, but their solution ended up on two different machines with not enough time to merge properly. I was a little surprised that no-one used itertools groupby, which is pretty much advertised as a drop-in for uniq.

You can see a few photos retweeted at the @ldnpydojo account. Back again in January, probably on the second Thursday. But watch the python-uk mailing list and @ldnpydojo for announcements.

PyConUK 2014: The Teachers

This is the third time that PyCon UK has organised a track especially for educators: really, for Primary & Secondary teachers, rather than for University lecturers. The first, a couple of years ago, was small, essentially a few hours within the main conference. The second, a whole Saturday last year, suffered from a belief that teachers would be too busy during the week and would prefer to come at the weekend. (In fact it seems they’re happy to get a day out from school on legitimate business such as learning about Python). This year we had upwards of thirty for the whole of Friday, students as well as experienced teachers.

You can read about some of the activities on offer and what they got out of them on their blogs and elsewhere. What I want to talk about is what I got out of it. I don’t think I learned anything absolutely new, but certain things were brought home to me more clearly.
I think that, as hackers (in Eric Raymond’s sense of that word), we expect teachers and pupils alike to be on fire with enthusiasm for programming, agog to learn more and to advance in this amazing world, and skilful enough to appreciate the subtle nuances and elegant constructs of the Python idiom. And we expect their schools to be 100% behind them, facilitating their initiatives, and supporting their ideas for learning in the 21st Century.

There surely are such people and institutions out there. But the picture painted by the teachers at PyCon UK was quite different. IT Administrators – whether school or county – can be restrictive in the extreme: disallowing access to the command prompt, enforcing bureaucratic processes for installing new packages, and limiting network access. At the same time, pupils may not be the excited and engaged proto-hackers you might have hoped for; they may have real difficulties with even the simplest of programming concepts. And the teachers are … teachers: people whose daily life is spent charting a course through the administrivia of modern-day schools, managing classrooms full of underappreciative pupils, and struggling to master for themselves some of the concepts they want to pass on to their pupils.

Like many in my situation, I started programming when I was 12, initially on my engineer Father’s programmable HP calculator and then, like so many others, on a BBC B. And I genuinely can’t remember a time when programming wasn’t intuitive. Of course, I’ve learnt and improved over the years. Of course there were things I didn’t understand; there still are. But the basic ideas of programming have always come easily. And I can find it a real challenge to put across concepts which are so very basic and whose explanation you’ve never needed to people to whom they don’t come naturally: to do the job of a teacher, in fact.

But that’s what each of us had to do for most of the teachers at PyCon UK and that’s what they have to do for most of their pupils. Even those teachers who have some experience in programming can struggle to visualise the solution to a more complex problem. To make matters worse, Computing is one of those subjects – like Music, perhaps – where a small number of the pupils can be streets ahead of the rest of the class. And maybe of the teacher.

On the Friday afternoon, after a morning of workshops, we had a Dojo-like session where teachers called out ideas for projects they’d be interested in pursuing with help from developers, and we developers attached ourselves to a group to offer advice. The group I joined was somewhat decided for me as one of the teachers was asking for help with an A2 project involving using a relational database to produce a simple room-booking website– and since my day job involves relational databases, I was pushed to the front to help a group of eight or so teachers.

In the discussion which followed, it became clear that, not only were many of the group of teachers hazy on the ideas of relational databases, but also of dynamic websites, plus the pieces of Python needed to pull those together. Another developer helpfully jumped in to propose Django, which brings us to the point I started to make above. Django has a good tutorial with a useful get-you-started admin mode, is well-documented, and has a strong and helpful community. But it requires a big level of buy-in from the pupils and, especially, from the teacher who will have to be able to help them.

“But there are forums,” you cry, “and mailing lists, and stackoverflow answers, and books, and lots of documentation”. And there are. But I was talking to teachers who have to fit a project like this into the structure of perhaps one or two classes a week plus homework among everything else. And something like Django is a big overhead. “But it’s easy!” It‘s not bad , if you already know what you’re talking about, or have unlimited time to play around and throw projects away. But, for this small project alone, I was having to pull together a headline course on relational databases and your possibilities using Python, with or without non-stdlib modules , plus the same thing for web programming, plus all the Python bits to make it all work. It was humbling to realise how many obstacles a teacher has to overcome to fulfil even the basics of the current computing curriculum.

As a proof-of-concept, I jotted down some notes on the spot, and ran up a couple of modules using sqlite and bottle (since it’s a one-file import which makes it easier to smuggle past restrictive installation régimes). The results are on my github.

During the Sprints on Monday (and on the way home) I decided to take it further, and to dust off an idea I had last year and which I hadn’t really pursued: One Screenful of Python. In last year’s Education track, I’d understood that one screenful of code was about right for one classroom session. So my idea was to produce useful, engaging, readable, snippets of Python which would fit, roughly, onto one screen and would produce an interesting result and illustrate some useful points of the Python idiom or of programming in general. It’s hosted in a github organisation.

It was quite clear that the project of building a website for room bookings using a relational database wasn’t going to fit on one screen even with some code gymnastics, which would in any case have defeated the pedagogical purpose of the exercise. So I restarted and produced a one-module project, built up over 13 steps, each building on the last (so a code-diff tool will produce a useful comparison). The result is in its own repo within the One Screenful organisation.

The code should run unchanged on 2.7 and 3.x; it should run cross-platform, especially targetting Windows & Raspberry Pi as they’re most likely to be found in the classroom; and it should work with the stdlib alone. These restrictions are an attempt to reduce possible difficulties teachers might face in getting it up and running. Sticking to the stdlib obviously precludes handy tools like Bottle (or your other lightweight web framework of choice), SqlAlchemy (or your ORM of choice) and whatever else might be useful. But it does simplify things. (pip install on Python 2.7 on Windows anyone ?).

But the most difficult restriction was in writing code which would be understood by A-level students. I’d struggled valiantly to pull back my hand and write simpler code. And then a teacher who kindly gave me feedback said that she thought the more able among her pupils might be able to cope with the code! This is the nub of the issue: the pupils who are gifted in this area can head off into the distance and work up full-stack Django apps from the online documentation and StackOverflow questions. But the run-of-the-mill average students need things to be kept simple to get them started.

If I have the time I’ll probably do a Git branch which will rework the final codebase in terms of, say, Bottle and SqlAlchemy. I don’t say that learners shouldn’t know about these things: they certainly should. I just think that every tool you add to a stack, no matter how useful, adds complexity. And if someone is a beginner, it might be better to stick to standard stuff. (I recognise that this is not a very strong argument since the code needed to manipulate SQL without an ORM is relatively verbose; likewise, using the built-in WSGI support). I also considered an approach of using git tags rather than the separate directories for the progressive disclosure of of the codebase. But, although it’s a neat idea, it’s an additional complication to cope with in the classroom.

So what did I get out of the Education Track? Well: that what many teachers need is simple code, easily installed, runnable without complications on different platforms. I’d like to be able to help, but I have commitments of my own which prevent me from easily giving much time to direct help in a classroom. But providing suitable code and advice is something I can do.