Pygame or App Development using Kivy or XCode?

19 May, 2018

Sunil writes:

I would, first of all, like to thank you for the amazing book you have written "Python for Kids"
It's really helped my nephew learn Coding in a very exciting and fun way.
He is now very keen on continuing with Python. He is 8.
But at this point, I do not know what would be the next set of things to teach him. Should we proceed with learning Pygame or App Development using Kivy or XCode. I am a little confused on this matter.
I tried a bit of reading online, but it did not help my decision making.

What would you suggest is the best Python learning path for an 8-year-old after having followed your book.

I'm quite partial to the idea of Pygame as a natural progression from the games in the book. Adapting the Bounce or Stickman game to use Pygame, instead of tkinter, seems like a good way to get started, and then Pygame has support for audio (mixer) and joystick modules, so there's opportunities to enhance and extend the games to add new features. This would be building on learning from the book, which I think is a nice way to move forward. It's certainly going to be the easiest way to get some instant feedback as well (since it's not hard to get up-and-running), so thumb's upfrom that perspective.

I don't know a lot about Kivy - so I can't really comment on how suitable it would be for an 8 year old -- but even if it proved too difficult, if he's interested in mobile apps, then I don't think that time would be wasted.

XCode will probably mean learning a new language (depending on what your nephew wants to do with it). If iOS apps, then the options are Objective-C or Swift -- which is not to say you're entirely limited to those languages, but you're going to find the most community support with one of the primary languages. Of the two, Swift is the most approachable (IMO), but I still wouldn't call that easy going for a child to pick up.

So with very limited experience in the other two options, I guess my personal preference would be Pygame, then Kivy, finally XCode. Do let me know how you get on...

Reference links for other readers:

A question about tkinter update

09 May, 2018

Feng writes:

I bought a chinese version of your book. when i tried the paddle ball at this step: 'Bounce (example 4) - ball moving up and down' at the first part of the code, you add a line tk.update(). I cannot see why this is necessary, since there are no balls moving at all. Then, i comment it with a '#'.

Now, it comes with a problem, i failed to see the ball move down, it seems stuck at the top line of the canvas. I tried to print the variable 'pos', and it shows as follows:
------------------(some part of the outcome)
[255.0, 1.0, 270.0, 16.0]
[255.0, 0.0, 270.0, 15.0]
[255.0, -1.0, 270.0, 14.0]
how did this happen, why the first 'tk.update()' cannot be omitted?

The first call to tk.update() isn't strictly necessary - but what it does do is to force a "wait" until all the Tk user interface events have been processed.

When you call pack to tell your Tk components to resize and display themselves in the right place, you're actually sending a message to a whole separate process (this is the Tk event loop). Let's imagine it took 1 minute for each component to set itself up, and you had 10 components in the window. If you called pack it wouldn't take 10 minutes to complete that function call -- it would actually complete almost instantly. Behind the scenes however, the components are busy re-arranging themselves to fit in the window (and in this imaginary scenario, that process would then take 10 minutes to complete).

Try running this code (create a file and run it in IDLE):

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)

You'll get 1. That's because the canvas hasn't finished rearranging itself by the time you call winfo_height. Now try typing the first 4 lines of the code into the IDLE shell -- wait a few seconds then enter the last line:


Now you'll get 400 (i.e. 400 pixels high). Because you've given the canvas time to complete.

In summary, pack is saying "ok Tk components, re-arrange yourselves on the screen" and update is saying: "ok Tk, I want to wait for that to complete". Which is why, if you remove the update call, inside the __init__ function of the Ball class, it calculates a height of 1, and the code no longer works correctly.

Trouble with turtles

11 Feb, 2018

Theodore M writes:

Hello. Working in python with my daughter, but stuck on this error:

Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "copyright", "credits" or "license()" for more information. >>> import turtle Traceback (most recent call last): File "<pyshell#0>", line 1, in import turtle File "/Users/mac/Documents/", line 2, in t=turtle.Pen() AttributeError: module 'turtle' has no attribute 'Pen'

It looks as if you might have created a file called in your Documents directory (/Users/mac/Documents), and because you're running IDLE from the same directory (I assume), that file is being loaded before the actual turtle module. If you delete this file and try again, hopefully you'll have more success.

Update: for people having a similar problem on Windows (or really any Operating System), who can't find the file to delete, one option is to enter this into the shell:

import turtle

That will give you the full path. For example:

>>> print(turtle.__file__)

Problem with paddle-ball animation

19 Feb, 2018

Hayden B writes:

I am trying to code the bouncing red ball in Chapter 13 but the animation is not working. I have checked the code, and it makes sense, but I am getting these errors when I run:

RESTART: C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\ Traceback (most recent call last):   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\", line 33, in <module>     ball.draw()   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\Files .py\", line 15, in draw     self.canvas.move(, self.x, self.y)   File "C:\Users\rf\AppData\Local\Programs\Python\Python36-32\lib\", line 2585, in move_ _, 'move') + args) _tkinter.TclError: invalid command name ".!canvas"

...and the red ball gets "stuck" at the top "jiggling" but not bouncing or returning down as it is supposed to. I cannot figure out what the problem is. Can you help?

Your code is almost right, there's just one thing you've mistyped. Here's a snippet from my code:

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)

And here's your code:

canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)

Check the difference in the last line. Why do the missing brackets cause such a problem? The reason is that Python can't calculate the height of the canvas (400 pixels) until you call pack() and then update(). You are calling tk.update which is effectively just dumping information about the function, rather than calling the function itself. Here's what happens if I try that code:

>>> tk.update
<bound method Misc.update of <tkinter.Tk object .>>

And, because you aren't actually calling the update function, this line...

        self.canvas_height = self.canvas.winfo_height()

...actually results in canvas_height being 1 pixel, rather than 400. As a consequence, your ball then gets stuck jiggling at the top of the screen because both these if-statements end up being true:

        if pos[1] <= 0:
             self.y = 1
        if pos[3] >= self.canvas_height:
             self.y = -1

(so pos[1] ends up being less than or equal to 0, and pos[3] ends up being >= to the canvas_height)

By the way, you can ignore the error message -- that has nothing to do with your code. When you close the game window, your program is still trying to call the move function and so you get an error message because the canvas no longer exists (effectively).

Hope that helps.

Restarting the Bounce game (revisited)

04 Mar, 2018

Robin T writes (excerpted):

I am currently at chapter 14, i already made my first game called "Bounce". When the game is over, i want the user to push a button or a mouse click to restart the game. But i don't know how to do this.

Someone else asked a similar question a few years ago, so here's my post from back then, with some ideas about adding a restart button: "Restarting the game". In terms of creating a function to restart the game, you might want to use the canvas coords function to move the ball and paddle back to their starting position, and then set the values of all the other variables to the same as they started as well (for example, setting the hit_bottom variable to False; if you've added a score, setting the score back to zero; and so on). coords takes 5 parameters: the id of the object to move, the x and y position and the width and height of the object. So moving both objects back to their starting position might look something like this:

self.canvas.coords(, 200, 300, 300, 310)
self.canvas.coords(, 245, 100, 260, 115)

Hopefully that helps.

Trouble with GIMP

29 Sep, 2018

Tom writes (excerpted):

I'm learning Python from your book and I'm finding it a great resource. However, I'm at the point where I'm creating the StickMan game and I'm having issues. I'm using an iMac running MacOS Sierra 10.12.6 The version of GIMP that I downloaded is 2.8.18. Specifically, I'm at Part III, chapter 15, "Creating the Game Elements-Preparing a Transparent Image". Steps 1 through 3 go well, but when I go to "Select -> All", there is no "All" in the "Select" menu. I am also having issues with the paintbrush as a dot. It shows up as a large square and will blot out most of the 27x30 image that I'm trying to paint. Gimp seems to be prompting me to add other layers, but I'm not clear as to how that will affect the image I'm trying to create.

I'm only using a slightly later version of GIMP than you at the moment (2.10), and I don't see any issues - though I'm not running Sierra, I doubt that makes a significant difference. For example, in terms of the Select menu, I can see All at the top:

Gimp Select menu

In terms of your problem with the brush, if you look at the brushes palette, the single pixel (1x1 square) is almost at the bottom:

Gimp Brushes Palette

(Not entirely sure what you're seeing, but hopefully those screenshots help?)

Finally, regarding layers in Gimp, those aren't necessarily an issue. When you export the image (as a gif or png or anything else) it should collapse the layers into one -- and even if you find them annoying, you can click on the top layer in the layers dialog, select the Layers menu, and then click Merge Down to collapse into the next layer in the list.

Modified IDLE

23 Sep, 2018

Dean B writes:

I'm on page 137 of your book Python For Kids (chapter 10). I noticed a sentence at the top of the page, and have a question on it. It says "This won't work if you're using the modified version of IDLE that we set up in Chapter 1." I didn't remember seeing anything in chapter 1 on a modified version of IDLE. I looked back through chapter 1, but still don't see anything on the matter.

Would you please tell me what page that is on? I'm more curious than anything. I was frustrated with the "New File" window so I did a search and found IDLEX extensions and installed that. It works quite well for me. I would like to know though how your modified version works.

I'm new to programming and after searching for a good programming language to start with I chose Python, and after looking through a lot of books I chose your book "Python For Kids". I’m a senior citizen and have found this book to be a great introduction to Python. Certainly not just for kids as long as the adults are okay with the kid like context. Works for me, and thanks for such a good book.

Apologies for the confusion there -- this was a miss when we updated the book for later versions of Python 3. When Python for Kids was released in 2013 (end of 2012), you needed to make a minor modification to the shortcut used for starting up IDLE, to turn off "subprocess mode". Without going into too much detail about what that is, effectively if you ran IDLE with subprocess mode on, some of the graphical examples (tkinter, etc) would cause the Shell to hang. This was fixed in a later version of the IDLE runtime, and I removed those instructions from the first chapter on installation -- but completely missed the reference on page 137. Thanks very much for letting me know and I've updated the errata here.

Python Kinderleicht

30 Jun, 2013

Python Kinderleicht cover This arrived in the mail from No Starch today.

Sehr cool!

The German translation of Python for Kids is available from the publisher dpunkt verlag and (probably others, but those were the first couple of links that popped up).

Tkinter problems on the Raspberry Pi

10 Jul, 2013

Ben writes:

I am 12 and I am reading your book, Python for Kids. I have recently confronted a problem with the module tkinter. I have recently got a rasberry pi to program on python. I am pretty sure that tkinter is already installed on python, but when I run something like:

def hello():     _print('hello there')_ from tkinter import * tk = Tk() btn = Button(tk, text='click me', command=hello) btn.pack()

There is nothing that pops up! I am frustrated and need help! Please help, me and my father are new to linux by the way and don't know what to do.

Ben is using Debian Linux on his Raspberry Pi. After a bit of to-ing and fro-ing, we eventually found that tkinter was definitely installed, but it looks like (according to this stackoverflow question that his father found) the tkinter window doesn't appear unless you use: tk.mainloop().

So if you're trying the code on page 178 (for example) on a Pi, you might need to add one line to get it to work successfully:

>>> from tkinter import *
>>> tk = Tk()
>>> canvas = Canvas(tk, width=400, height=400)
>>> canvas.pack()
>>> canvas.create_arc(10, 10, 200, 80, extent=45, style=ARC)
>>> canvas.create_arc(10, 80, 200, 160, extent=90, style=ARC)
>>> canvas.create_arc(10, 160, 200, 240, extent=135, style=ARC)
>>> canvas.create_arc(10, 240, 200, 320, extent=180, style=ARC)
>>> canvas.create_arc(10, 320, 200, 400, extent=359, style=ARC)###
>>> tk.mainloop()

Problem with the turtle module

30 Oct, 2013

Mark F writes:

I think that it's a great book but I am running into one issue. If you're not too busy, I'm hoping you could answer it for me. In Chapter 8, Classes and Objects, you reintroduce the turtle module. You say that we can create 'an object of the pen class,' which makes sense.

import turtle
avery = turtle.pen()
kate = turtle.pen()

However, when I attempt to move the turtle using either one of those objects, I get this error:

Traceback (most recent call last):
   File "<pyshell#3>", line 1, in
AttributeError: 'dict' object has no attribute 'forward'

In fact, the only time I can get the turtle to move is if i simply type in turtle.forward(). I am using version 3.3 but have tried with 3.2 and encounter the same error. Please let me know why I keep getting this error so that I can keep moving forward.

If you compare your code snippet above, with the example in the book, there's one fairly obvious difference: lowercase "p" versus uppercase "P". The question is, why is it such a problem? In the turtle module, Pen and pen are two distinct things. We can see the difference if we run the Python console (or Shell), and try out the following code:

>>> import turtle
>>> turtle.pen
<function pen at 0x10117fe60>
>>> turtle.Pen
<class turtle.Turtle>

Without the brackets (i.e. without entering pen() or Pen()), Python just prints out a simple description, so we can see that pen is a function, and Pen is a class (good rule of thumb: names which start with an uppercase letter are generally classes, names with a lowercase letter are functions, variables, and so on). For the example code, we want to create a Pen object (we don't want to call the pen function) - so if you change your code to...

import turtle
avery = turtle.Pen()
kate = turtle.Pen() should have a bit more success.

Tcl/Tk warning message when starting IDLE

31 Dec, 2013

Stan W writes (NB. edited for brevity):

Over the last couple of days I have started using your great book with my two sons (13 and 15 years old). I'm reaching out to you with the following question because I have noticed other people asking about the same issue online, with at least one mentioning your book, so I think you posting the question and answer to your blog might help other people in addition to me and my sons.

We are using Mac OSX and have installed Python 3.3.3 from, and are getting this message when opening IDLE:

"WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit for current information."

I have installed "Mac OS X 64-bit/32-bit Installer (3.3.3) for Mac OS X 10.6 and later" (file: python-3.3.3-macosx10.6.dmg) and installed the "ActiveTcl 8.6.1 for Mac OS X (10.5+, x86_64/x86)" (file: ActiveTcl8., but IDLE keeps showing the same error message.

Thank you very much for any help you can provide!

I'm not convinced ActiveTcl 8.6.1 is the right version to install - I suspect rather than installing the latest and greatest, you should be using version Python (and thus IDLE) will probably be using the latest 8.5 version of Tcl/Tk (i.e. 8.5.x) — you're installing a completely different version (8.6), which it's not looking for at all. Hence even though you think you've re-installed, you'll still be getting the same error message.

Hope that helps.

Left and right, or top and bottom

14 Dec, 2013

Matthias writes:

My name is Matthias and I am 7 years old and I like Python. I knew a little about Python before I read your book, but I am learning more by reading your book. I like your book.

I think on page 202 is a little mistake. You wrote:

"We'll use this new object variable in the draw function to see if the ball has hit the top or bottom of the canvas:"

Shouldn't it be "left or right sides of the canvas" instead?

Hi Matthias. You're doing well to have gotten as far as you have, at 7 years of age. Well done!

You're absolutely right about the mistake, and I've updated the errata accordingly. Thanks very much for the "bug report". ツ

Problems with files

19 May, 2013

Evan writes:

I have a Windows 8 PC, and have installed Python 3.3 onto it, and worked my way up to the last part of chapter 9 in your book with no major problems. But now I am stuck in the last part of chapter 9. The first time I tried to save a notepad txt file to the C: location, access was denied, because the user account I was using was not the dominant user account. I fixed this by running the notepad as the administrator, and was able to save the txt file to the C: location. Opening and printing the contents of the txt file worked fine after that. My next problem (and still is a problem) was writing to the text file. The first error message said access was denied. I fixed this also by going to the administrator's user account and allowed the user settings I was working on to have almost complete control over all the C: location. Now when I try to write to the txt file, I get a different error: "OSError: [Errno 22] Invalid argument: 'c:\myfile.txt'. Please help me!

Hi Evan. The final error you're getting is generally caused by an invalid filename (for example, if you had two colons rather than one) - but I don't see that problem in the example you sent. So I'm not quite sure what's gone wrong there.

In terms of the example in the book, I've added a new entry in the errata (see the section Page 123). The directions should instead tell you to save the file to your user directory - something like: c:\\Users\\Evan - rather than to c:\. Check the errata and hopefully that should work for you.

Tkinter colorchooser problems

02 May, 2013

Michal writes:

My son has found a problem. It is regarding:

from tkinter import *

It is not working and I cannot help him. On the python shell he gets an error:

Traceback (most recent call last):
File "", line 2, in <module>
NameError: name 'colorchooser' is not defined

Could you help please.

This is an odd one. If I try the code in the Shell, the color chooser is available as expected:


But if I try the same code in the command-line console, I get a similar error:


The only way I can reproduce the problem in the Shell is when I don't run it in "No Subprocess" mode - that's if you don't follow the installation instructions, in Chapter 1 of the book, and just run the Shell/IDLE as it was installed (without modifying the shortcut):


You can get around this, by directly importing the colorchooser module like so:

>>> import tkinter.colorchooser
>>> tkinter.colorchooser.askcolor()

But you'll probably hit problems if you try to call the askcolor function (the second line in that snippet of code above).

All of which is rather messy and confusing. My suggestion would be to make sure you see the "No Subprocess" message when you run IDLE, and if not, revisit Chapter 1. If you do see the message on startup, and still get the error (which I haven't managed to do, but I'm guessing might be possible), try the sample code above, and see if that works for you. Good luck!

More information updated July 2020 here.

Lander Solution Posted

27 May, 2013

A partial solution to the Lunar Lander 'Programming Puzzle' has just been posted.

One versus two underscores

20 May, 2013

Omer writes:

I am currently on Chapter 13 and I have come across a problem that I cannot seem to figure out. I am in the section 'Creating the Ball Class'. I wrote the code the way that you have described in the book, and I am getting the following error:

Traceback (most recent call last): File "C:/Users/Omer/Desktop/Master Functions/", line 22, in <module> ball = Ball(canvas, 'red') TypeError: object.__new__() takes no parameters

However, when I copied the code from your website, it worked perfectly. I put my code and your code side by side and I cannot seem to figure out where the mistake is. Can you help me figure this out.

It's easy to miss something when you're manually comparing two files. The best way to do this sort of thing is to use a diff tool. You're using Windows, so something like winmerge would do the trick. In any case, when I diff the files you sent using the command line diff tool, I see the following difference:

<     def _init_(self, canvas, color):
>     def __init__(self, canvas, color):

So in your code you've got a single underscore on either side of init - which explains the error you're getting. Because you haven't defined the __init__ function correctly, Python assumes a default with no parameters. Fix that, and the code should work as expected. Good luck!

Addendum (for anyone searching for similar errors): on Windows, you'll probably get a message like "TypeError: Ball() takes no arguments", but ultimately the cause is exactly the same.

Python for Kids on the Raspberry Pi

10 Jan, 2013

I finally managed to find enough bits-and-pieces to get a Raspberry Pi (borrowed from a friend - thanks Matt!) up and running, in order to test out the code from Python for Kids. A USB charger for an old Nokia phone, a somewhat dodgy-looking USB power adaptor from the bottom of a cobweb-filled box in the back room, a wireless mouse (the base for which had managed to hide itself on the opposite side of the house), a bent network cable (surprisingly still functional), and a powerline adaptor scavenged from the TV. In the end the only thing missing was a USB keyboard, which finally arrived in the mail this morning.

Raspbian menu It looks like all the code works fine, and Python3 is installed by default on the Raspbian operating system, so there's not a lot required to install out of the box. There is one thing to be aware of - do not use the IDLE3 icon which is on the desktop by default (at least not when you're running the graphics code in the book). Instead, go to the Other menu, and choose IDLE (Python 3.2) (click on the screenshot to see what you should be looking for). This runs IDLE in "No subprocess" mode, so modules such as turtle will run correctly.

However, to use GIMP (the graphics program we use in Chapter 15), you will need to install it first:

  1. Make sure your Raspberry Pi is connected to the internet
  2. Open a terminal (select the Other menu, and then LXTerminal)
  3. Update the package list (might not be necessary, but just in case) by entering the following command: sudo apt-get update
  4. Once completed, install GIMP by running this command: sudo apt-get install gimp

After installation, you'll find a new menu option in the Graphics menu: GNU Image Manipulation Program.

That should be all you need to get started with the Raspberry Pi.

The Front Page

31 Jan, 2013 Very cool. The front page of

Officially geeked out.

Puzzle 1 Solution

01 Jan, 2013

Happy New Year!

The solution to Programming Puzzle 1 has been added to the puzzle page - actually it was updated just before Christmas, but I've been entirely too lazy busy to post about it. ツ

Puzzles 2 and 3

21 Jan, 2013

The solution to Programming Puzzle 2 has just been added to the puzzle's page, and challenge number 3 has been posted.

Stickman Elevators

25 Jan, 2013

Henry Angeles writes:

I'm not a programmer, so when my kid asked me to make an elevator in the stickman game I totally failed. I can get the platform to move up and down, but when the elevator starts going up with the stickman on it, hilarity ensues.

I guess at the end of the day i'm asking how this can be done. Thanks for your time.

I'm not surprised you found it difficult. It caused a fair amount of head scratching until I realised the trick to getting this working. If you used the code for the horizontal platforms in PythonForKidsSolutions.pdf as the basis for your elevator, your stick figure probably slips through the platform as soon as he touches it (or potentially rockets off up the screen depending upon your code). The elevator moves at a different speed to the stick figure, so you need to match that speed when the figure lands on the platform - and you can't rely on the basic collision detection code as it's written in that example.

A new programming puzzle, for this, has been added to the puzzles page - check back in a week or two for the full solution.

Between Giants

04 Apr, 2013

Similar in scale to a gnat between two giants...? ツ

Solution 6

15 Apr, 2013

The solution to programming puzzle #6 has just been posted.

Python on the Web?

18 Apr, 2013

Dean writes:

I'm 13, I live in the US, and I just finished reading your excellent book "Python for Kids". After I finished the book I had two questions. First I was curious if it is possible to put a python game on a website to play? The other question I had was what was the hardest project you have ever worked on, how long did it take you, and what language was it in?

There are a few implementations of Python that will work inside the browser, but as far as I know they don't support all of Python's features (such as the tkinter module, or PyGame, for example). So it would be rather difficult to write a game that could be played on a website (in my opinion). If that's something you want to do, you'd be better off learning Javascript (the standard programming language used in all browsers). If you google for "javascript and html5 games development", you'll find a lot of information out there. Luckily, once you've learned one programming language, it's a lot easier to learn the next.

In terms of hardest project, that's a difficult question to answer. I've worked on projects which were hard because the amount of code in the application was huge, and because there were a lot of "moving parts" - lots of communication between different systems. In terms of complicated systems, I recall one project (which I spent about 18 months on with a team of 8 or 9 people) where I had to write the code for very complicated graphical reports -- that was hard because I had to remember mathematics I learned years before (the programming language in that case was Java and some Python as well).

Hope that helps.

Puzzle Updates

12 Feb, 2013

The solution to Programming Puzzle #4 has been posted, and you can also find a new puzzle added here.

PFK Errata

20 Feb, 2013

Piotr Słowik writes:

I'm learning how to code from your book. It's great! First time in my life I'm starting to understand how to write code and make it work ;) You're the first person whose teachings make sense to me!

But I have problem with this example:

>>> v = sys.stdin.readline(13) He who laughs last thinks slowest >>> print(v) He who laughs

Whatever I do I get this error:

readline() takes 1 positional argument but 2 were given

I'm using Python 3.3. Please, help.

Thanks for the email Piotr. It looks like you've found the first 'bug' in the book. That example definitely works -- but it doesn't work in the Python Shell. If you try in the Console, you won't get the error.

The reason for the difference is that the Shell does some magic to replace the stdin object with a version of its own -- and its version of the readline function doesn't have a parameter for the maximum number of characters (hence you get an unexpected error message).

I've added this to the errata page accordingly.


08 Mar, 2013

Rather belatedly... the solution to Puzzle #5 was posted a few days ago. Puzzle #6 is now also available.

Also rather belatedly, Dave Winer has an interesting take on the recent promotional video. Stand out quote:

Primarily you should do it (ed: programming) because you love it, because it's fun -- because it's wonderful to create machines with your mind. Hugely empowering. Emotionally gratifying. Software is math-in-motion. It's a miracle of the mind. And if you can do it, really well, there's absolutely nothing like it.

What is -n for

28 Aug, 2013

John writes:

Quick question regarding the -n used in the shortcut for IDLE. I realize that it starts IDLE with no subprocesses, but what does that mean and why do we want to do it?

There's precious little on the net describing what the -n switch does. From the IDLE documentation:

If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible.

Which, I admit, doesn't help a huge amount...

For the purposes of Python for Kids however, all you really need to know is that certain graphical libraries (such as turtle and, I seem to recall, tkinter) will exhibit weird behaviour (such as locking up/hanging) if you don't run IDLE using the -n switch.

Loop confusion

27 Sep, 2013

Justin B writes:

I recently started the section on "For Loops" and am somewhat confused about something. The section (page 55) runs a loop for "HugeHairyPants." I setup the loop as you indicated and actually understood the result just fine.

However, I decided to add a variable in the mix and went one step further. Here is my script:

hugehairypants = ['huge', 'hairy', 'pants'] for i in hugehairypants:     _print(i)_     _for j in hugehairypants:_         _print(j)_         _for k in hugehairypants:_             _print(k)_

This loop doesn't seem to follow the same progression of the other loop or maybe I just don't understand it correctly. I figured it would print a variable from i and then j and then print the full loop of items in k, but it doesn't seem to do that. If you have a moment, could explain how this loop would work?

If we look at your code and mark each loop, then mark the output as well, and indent each line in terms of the loop it matches, hopefully it might help you see what's happening:

hugehairypants = ['huge', 'hairy', 'pants']
for i in hugehairypants:      # LOOP 1
    for j in hugehairypants:    # LOOP 2
        for k in hugehairypants:    # LOOP 3

And the output:

huge   (LOOP 1, first time)
    huge   (LOOP 2, first time)
        huge   (LOOP 3, first time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    hairy  (LOOP 2, first time)
        huge   (LOOP 3, second time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    pants  (LOOP 2, first time)
        huge   (LOOP 3, third time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
hairy  (LOOP 1, first time)
    huge   (LOOP 2, second time)
        huge   (LOOP 3, fourth time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    hairy  (LOOP 2, second time)
        huge   (LOOP 3, fifth time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    pants  (LOOP 2, second time)
        huge   (LOOP 3, sixth time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
pants  (LOOP 1, first time)
    huge  (LOOP 2, third time)
        huge   (LOOP 3, seventh time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    hairy  (LOOP 2, third time)
        huge   (LOOP 3, eighth time)
        hairy  (LOOP 3)
        pants  (LOOP 3)
    pants  (LOOP 2, third time)
        huge   (LOOP 3, ninth time)
        hairy  (LOOP 3)
        pants  (LOOP 3)

So loop 1 outputs the list once, loop 2 outputs the list three times, and loop 3 outputs the list nine times in total.

As a side note, we could have also altered the code to do the indentation for us:

hugehairypants = ['huge', 'hairy', 'pants']
for i in hugehairypants:      # LOOP 1
    for j in hugehairypants:    # LOOP 2
        print('    %s' % j)
        for k in hugehairypants:    # LOOP 3
            print('        %s' % k)

And, while sometimes it's a good idea to work things out by hand (as I did in the example output above), just so you can be sure you understand the process, we could even use counters to print out the number of times we've hit each loop, rather than figuring it out manually:

time_label = ['','first','second','third','fourth','fifth','sixth','seventh','eighth','ninth']
i_counter = 0
j_counter = 0
k_counter = 0
hugehairypants = ['huge', 'hairy', 'pants']
for i in hugehairypants:      # LOOP 1
    if i == 'huge':
        i_counter += 1
    print('%s (LOOP 1, %s time)' % (i, time_label[i_counter]))
    for j in hugehairypants:    # LOOP 2
        if j == 'huge':
            j_counter += 1
        print('    %s (LOOP 2, %s time)' % (j, time_label[j_counter]))
        for k in hugehairypants:    # LOOP 3
            if k == 'huge':
                k_counter += 1
            print('        %s (LOOP 3, %s time)' % (k, time_label[k_counter]))

Python installation confusion on Mac OS X

20 Sep, 2013

Justin J writes:

I installed python 3.3.2 for my macbook running version 10.6.8 and typed this in, open -a "/Applications/Python 3.2/" --args -n and it didn't work:

"The action Run Shell Script encountered an error. Check the action's properties and try running the workflow again"

I installed both versions 32 bit and 64/32 bit and it still didn't work.

I'm assuming because I installed 3.3.2, I had to change it to open -a "/Applications/Python 3.3/" --args -n. In other words change Python 3.2 to Python 3.3. Then it worked! Unfortunately I think it was running on the 64/32 version which python mentioned something about ActiveTcl 8.5. It recommended I download 32, so I got rid of 64/32 and re-downloaded 32 bit and it finally gave me no error in the shell.

I thought I'd ask if this was an ok thing for me to do?

As per the instructions on this page, you'll need to install ActiveTcl in order for IDLE and Tkinter to work properly (both are used heavily in the book) with Mac OS X 10.6.

ActiveState have a dmg installation file, so once you've downloaded it, double-click on the file, and a dialog will appear:

ActiveTcl installation dialog

You may need to control-click on the ActiveTcl package, if you double-click and get the error message "ActiveTcl-8.5.pkg can't be opened because it is from an unidentified developer". So if that error message appears, hold down the Control key, click on the icon and select Open from the menu displayed, then click Open on the following screen. Click through the next few screens (you'll be asked to agree to the license and so on), and on the final screen, once you click Install, you'll get promoted for an administrator username & password.

Apart from that, your change to the open command is correct, so once ActiveTcl is installed, you should be good to go.

Problems installing Python

06 Jun, 2013

Chana writes:

Python does not install on my computer, and I'm not sure why.

Windows 7 Home Premium 64-bit operating system

Everything works fine until you get to the part that says "Please wait while the installer installs python..." After about half an hour, a little window pops up that says that the installer is no longer responding.

According to this page... you should try disabling UAC. I'm not a home Windows user, but a quick google found this: Hopefully that fixes the problem.

O'Reilly Media Discounts

05 Jun, 2013

Apparently Python for Kids is featured in O'Reilly Media's "Learn to Program ebooks" promotion (save 50% on introductory programming ebooks). More details can be found here.

Scratch or Python?

24 Jun, 2013

Marvin writes:

I have a 10 year old son who is interested in programming. He really loves playing games so I thought he should learn how they are created. I am a bit confused on which language to have him start.

My question is should he start with Scratch (and for how long?) or should I start him with the Python language (with your book)? I've also heard about Ruby for Kids. Which is the easier path for him to start.?

I will greatly appreciate you thoughts on how he should get started?

Well, by all means, my book... ツ

But to be entirely honest, it's a difficult question to answer. Some kids will find the visual nature of Scratch attractive. And it may be a natural progression to go from something like Scratch to a more traditional programming language (not something I have a lot of experience with, given I started with a traditional programming language when I was a kid). But, if he has a modicum of technical ability, and an interest in how games are really created, then learning a traditional programming language may be the better path.

Either way, I don't think it will do any harm to start with Scratch, and progress to Python if he finds Scratch a little mundane - or vice versa, start with Python and go back to Scratch if he finds Python too advanced. However, in terms of Ruby, I can't really comment, as it's not a language I have much experience with.

Not sure that particularly helps, but good luck anyway.

Deprecated switch

13 Jul, 2015

Sandy S writes:

I just purchased 3 copies of "Python for Kids" so that my 2 sons and I can begin our quest! Anyway I hate to bug you with this but we just downloaded the latest version of the Python suite and the –n switch for IDLE startup has a message about "being deprecated since version 3.4". Is there another startup scheme that we should use instead? Also what do you recommend, in addition to the fine book, to enhance the learning process? My sons are middle-school age and very math/science savvy. I have a hardware engineering background but no programming to speak of.

The -n switch is deprecated, but not yet removed. So it still works fine with that switch for the moment. I did see some discussion about it on one of the Python mailing lists (forget which now) but I don’t think there was a conclusion about what happens in the future with something like IDLE and the use of tkinter (perhaps someone else reads this and lets me know - in which case, I'll post their message here). In any case, safe to use.

In terms of enhancing the learning process, I'd say once they've gone through the book (at least covered the basics of programming) picking a project is a good idea. Static learning is fine up to a point (even working through examples in the book), but what really cements the learning process is finding something you actually want to work on. It doesn't matter what sort of project, game or otherwise. As long as it's something your boys are interested in (also think about things like the raspberry pi and robotics and so on — since you've got a hardware background that'll be a useful crossover).

Hope that helps.

Error opening IDLE on Mac OS X 10.6

10 Jan, 2015

Lucas writes (excerpted):

When I try to open IDLE as instructed on page 11 I get an error message.

Error dialog
> _Any suggestions?_

It depends on which version of Python you're running, but if you've installed the latest (3.4.2), then instead of putting the following in Automator:

open -a "/Applications/Python 3.4/" --args -n

Try putting this instead:

/Library/Frameworks/Python.framework/Versions/3.4/bin/idle3.4 -n

The reason the text in the book doesn't work is a difference between Automator in versions of OS X prior to 10.7 (I believe 10.7, anyway) and later versions of the operating system.

Problem with IF statements

26 Feb, 2015

Art S writes (excerpted):

First, let me say that I am having a great time learning Python from Python for Kids, even though I am just a kid at heart. I'm an old, old guy (I'll be 52 in April), but my students keep me young - I've been teaching high school mathematics for 25 years, and I am finally getting around to checking "Learn Python" off of my to-do list.

Here's the problem. All of my code has been running fine through IDLE until I got to the chapter on IF statements. When I typed into IDLE the first example from Chapter 5, page 54, nothing happened - the string 'You are too old!' (coincidence?) was not returned. All of the other examples involving IF's lead to the same result - nothing.


I thought I would give it one more try, just to be sure. When I did, I accidentally hit enter twice, and the desired output appeared. I feel good that it worked, but why should I have to hit enter twice?

So there's nothing you're actually doing wrong here. When you hit enter after typing the second line (the print part), Python is just waiting for the next statement in that block of code. Python uses white-space for the program structure, so the only way it knows you've actually finished that particular block of code, is when you hit enter again on the next line. So Python only runs the code once you've actually said you've finished... and the way you say you're finished, in this case, is to hit enter on an empty line.


Miquel C writes:

Do you know where to learn Python? I've been searching and I've only found Codecademy. I'd be very happy if you know where to go from Python For Kids. All kind of learning would be great.

I also downloaded an IRC bot, and I've translated it to my language. I've been looking the code and learning a bit.

Once you've mastered the basics of programming, my suggestion would be to find a small project to work on. Rather than looking at other people's code, or reading another, more advanced book, try creating your own version of an application you're interested in. It should be challenging, but not impossible. For example, when I was younger, I learned a new programming language by creating my own version of Tetris. You'll hit problems you don't know how to solve, so you'll end up reading the Python documentation, or googling to find the answers, or asking questions on sites like StackOverflow. But that's the one of the best ways to carry on learning (in my opinion).

Tkinter mainloop issue on Raspberry Pi

27 Aug, 2015

Martin writes:

First of all thank you for writing "Python for Kids". It's a great book and offers "instant gratification". My 8-year-old is already hacking his way through the pages on his brand new Raspberry Pi.

He (we) ran into a bit of trouble when we started playing with Tkinter.

Your initial examples don't ever call mainloop() or update(). Turns out, on the Raspi, in IDLE, those examples don't work as expected - nothing appears on screen. Until you run mainloop() that is. raspberry pi screenshot

If you run a pure python3 interpreter inside a shell window, your examples work. [They will also not work on Windows inside a Python 2.7.10 IDLE.]

Could you throw any light on why things work without calling mainloop() on some setups but not on others?

Turns out that trying to reproduce your problem - without having a RPi to hand - was a lot more difficult than I expected. Even after getting Raspbian going with QEMU, I couldn't get a menu to display so that I could run IDLE (solution: create an empty file, and from the file's context menu you can then access the Terminal). However, when I ran IDLE, it only worked in "no subprocess mode" (see the first chapter of the book). If I run without specifying -n, I get the following error:

qemu error (small image)

Only after going through the above, did I remember that there was an issue with IDLE & tkinter on Python 3.2 (when running without -n). And sure enough, when running with 3.2 on my PC, I get the exact same problem (it doesn't occur with later versions of Python).

Best thing you can do, is to run IDLE with the -n flag - the turtle/tkinter code you run will be more stable as a consequence (and there's no need to call mainloop).

(PS. as for Python 2.7.x, many of the code samples won't work - the book is only intended to be used with Python 3.x)

Python 3.5 beta issue on Windows

22 Aug, 2015

Tony writes:

I have installed Python 3.5.0b3, and when I tried to make the shortcut, it looked very different from the book's examples and I did not get the toolbar with "File", "Edit", "Options", etc. on the top. Please tell me how to correctly complete the installation process. Thank you, and I hope to hear back.

I'm not sure exactly what error you're getting, but I would suggest that while learning programming, you should probably use the latest release version of Python, rather than the beta. So at time of writing, that's version 3.4.3.

I do know of one problem with 3.5, where you need to move the DLL found in directory c:\Python35\DLLs\Microsoft.VC140.CRT, up one level (to directory c:\Python35\DLLs), in order to get tkinter working -- which I guess could be part of your problem (as detailed here:

So that's simply moving the file here:

microsoft.vc140.crt file - original location

to here:

microsoft.vc140.crt file - new location

NOTE: this is no longer required for the release version of 3.5 (it was only necessary for the beta versions)

Syntax error in

15 Aug, 2015

I have recently bought your book, Python For Kids and I think it's great and easy to understand except for one small thing.

It tells me to put this into the Shell:

spaces = ' ' * 25
print('%s 12 Butts wynd' % spaces)
print('%s Twinklebottom heath') % spaces)
print('Dear Sir')

I do what it says, I click run module, but I get this error:
error in editor window

I'm new to this, so I probably made some extremely stupid mistake, and i'm sorry if this is the wrong place to ask.

When I enter your code, I get the same error. But once I click OK, in the editor window I see the following:
error in editor window

That red highlight, on the third line down, shows you on where the error has occurred - and hopefully gives an idea about what might have gone wrong. In this case, Python isn't expecting a bracket at the end, because you've got one earlier in the line: print('%s Twinklebottom heath') % spaces). If you remove that bracket -- it should look like this print('%s Twinklebottom heath' % spaces) -- you'll find the program runs as expected.

Stickman Refusing To Move

17 Jul, 2017

Haran R writes:

I tried out the code for the two games and have successfully run the first game (bounce). The second game however did not run like how i wished it to. I followed the book’s instructions to the letter, used the GIMP software to create the images, saved it in a directory and saved the code in the same directory. The graphics came out fine but unfortunately I have not been able to get the stickman to move. I have followed the coding in the book to the letter and have checked my code against the coding in the book multiple times and i can see no mistakes.

The problem is with the indentation in your Stick Man class. If you look at the indentation of your code...

indentation 1

and then compare with mine...

indentation 2

...hopefully you'll see where you've gone wrong (if it's not immediately obvious, take a look at the vertical line coming down from the animate function in each of the code samples, and you'll see where the indentation isn't right). When I fixed the indentation on your code, it worked perfectly -- so you were almost there.

Hope that helps.

Multiplying Strings

11 Oct, 2017

Robin L writes (excerpted):

I am trying to teach myself how to code and thought this was a good place to begin. I am having trouble with the "multiplying strings" section. I don't know anyone else who codes so I am hoping that you are still available at this email. This is the part about printing a letter in the shell. For some reason when I run mine the "print()" keeps actually printing "()".

Can you please help me figure out what I am doing wrong?

There's a pretty major difference between printing with older versions of Python (Python2.7 and earlier) and newer versions (Python3 and later). In Python2, print is a statement, which means this works fine:

print "hi there"

If you try that in Python3, you'll get an error:

print "hi there"
  File "<stdin>", line 1
    print "hi there"
SyntaxError: Missing parentheses in call to 'print'

That's because print in Python3 is a function not a statement.

Why does that make a difference? In Python2, this code...

print() a print statement followed by an empty tuple. You're effectively telling Python to "print this empty tuple", and by quirk of the way the print statement works, you get (). The exact same code in Python3 is a function name (print) followed by an open bracket, no parameters, and a closing bracket. You're providing no parameters and the function prints nothing as a consequence. And that, basically, is the difference.

Cutting a long story short - all you're doing wrong is running an older version of Python. Check chapter one, and follow the instructions to install Python3, and the code will work as you expect.

Tcl Error

12 May, 2017

丁明 writes (edited for spelling):

In your book <<python for kids>> chapter 13, when I run the program, the python shell has a error I can't understand. my python version 3.6.0. Thank you for your reply!!


I'm not sure if the Chinese edition has captured the text on page 199 of the English version of the book:

You may see error messages written to the shell when you close the game window. This is because when you close the window, the code is breaking out of the while loop, and Python is complaining about it.

The is exactly the error you are seeing when you run that code and then close the window. You are stopping (interrupting) Python while it is running the code, and an error message is displayed as a consequence.

Basically, you can ignore the message, but if you want to know how to get rid of it for good, one option is to replace the loop at the bottom:

while True:

...with this...

    while True:
except TclError:

You can find more about error handling here:

How Many Hours

11 Nov, 2017

Xing Y writes:

This is Xing Yanchao from the city of Qingdao, Shandong province, China, a big beautiful coastal city with 7 million citizens. I'm very interested in teaching kids to program, and plan to choose your book as the teaching material (In Chinese, ^_^). The kids may be between 8~12, how many hours do you suggest for us to finish the whole book?

Thank you in advance!

I think at least an hour a chapter for Part 1 of the book, but the chapters on functions, modules, classes and objects will probably take a bit longer. 12-15 hours is probably reasonable to cover most of Part 1 in a classroom setting, especially considering there should be a bit of time for kids to play around and try things for themselves, rather than following it exactly. Learn through play is important, particularly with a subject that can be pretty dry. Parts 2 and 3 are more difficult to estimate. I would actually suggest to just use Part 1 in the class, then let the kids come up with projects for themselves, and use the last two parts of the book as a reference (for example, let them create something for themselves, but use chapters 13-18 to figure out some of what they decide to do). Just a thought.


18 Jan, 2017

Isai writes:

I am having trouble with this code in page 176:

from tkinter import * colorchooser.askcolor()

When I load it into IDLE, I get a blank canvas, and I can't close it, I have to restart the shell.

I have installed the proper ActiveTcl version (8.5), and no longer get the message giving me errors on startup.

When I run the previous code I was playing with (page 174), the canvas pops up and it all works again. Weirdly enough, the color picker pops up unprompted! I noticed that it does not bring up any buttons that appear in your book: [OK] [Cancel].

That's a bit of a gap in the book, because it doesn't make it clear that you need to create an instance of the top-level Tk widget first, before running that particular example (using tk = Tk()). So the first time you run this function: colorchooser.askcolor(), it's hanging, waiting for something that isn't there yet. Then you run the code on the previous page (which does create the Tk object), and that's when you suddenly get a popup dialog with the colorchooser in it.

So the code should really look like this:

from tkinter import *
from tkinter import colorchooser
tk = Tk()

When you run that, you should then get the colorchooser dialog immediately.

Update #1: One step I missed, is a call to tk.update(), which forces tk to update the screen. Once that's executed, the chooser will appear. The example is updated above.

Update #2: On Windows you need to explicitly import colorchooser for the code to work properly (example updated again).

That's pants!

06 Apr, 2017

Lee writes:

I'm not fully understanding the HugeHairyPants program on pages 72-73 of Python For Kids. I initially thought that the loop would produce "huge huge hairy hairy pants pants," reasoning that the program would assign the first value to i, then the identical value to j, and continue the loop. So why is the variable j assigned all of the values? My thought was that the program commands i to be the first variable ('huge'), then stops there because the variable j is introduced next. Since there is no other variables after j, it then gets assigned every variable. Is this correct? (It doesn't sound right to me, though.)

So let's break the code down a bit more then. Here's the list...

hugehairypants = ['huge', 'hairy', 'pants']

...and then the first two lines of the loop code:

for i in hugehairypants:

If we run this code right now we get:


Each time the value in i is (effectively) replaced with the next value in the list (it's actually not quite as simple as that, but it can be easier to think of it that way when you start programming).

It's important to remember that every time we loop here, we're executing all the statements in the block of code - that's the indented part. And that's why if we look at the original example...

for i in hugehairypants:
    for j in hugehairypants:
        print(j) first executes print(i), then it executes the second for-loop - that's looping over the hugehairypants list again, calling print(j) three times, then back to print(i) again, and so on. If we just look at the print statements Python is executing in these two loops, this is what it looks like:

print(i) # first for-loop - the value in i is now 'huge'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'
print(i) # first for-loop - the value in i is now 'hairy'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'
print(i) # first for-loop - the value in i is now 'pants'
print(j) # second for-loop - the value in j is now 'huge'
print(j) # second for-loop - the value in j is now 'hairy'
print(j) # second for-loop - the value in j is now 'pants'

If you need something more visual, I suggest drawing two rectangles on a piece of paper with 3 cells. Write the 3 values from the list in the cells (obviously it's not really two lists, but easier this way). Get two small coins; the first coin marks the value in i, the second coin marks the value in j. Work through the code as though you were running it yourself - move each coin to show how the value changes as we loop:

Visual guide

Windows 10

09 Apr, 2017

I've come across some uncorroborated reports that some of the instructions, or examples, in Python for Kids don't work with Windows 10. Uncorroborated because it's unfortunately nothing more than "it don't work". Not spectacularly useful, so I've finally gotten around to installing Windows 10 in VirtualBox to test this out.

Instructions for Python installation remain pretty much the same, except that the latest version of Python is now 3.6, whereas on the last printing of PfK, it was 3.5. The results of installation aren't too dissimilar to Windows 7 either:

windows-10 start menu (small image)

I cherry-picked a few of the code samples at the beginning of the book to test, but wasn't expecting any of those to be a problem (they weren't), and then went through the more complicated code (turtle, tkinter) in the rest. Everything works as expected, except there is a little bit of graphical weirdness in the Bounce game (chapters 13, 14) where the ball seems to deform as it moves. I'm pretty certain this is an artifact of using Windows inside VirtualBox (I've never found animated graphics to work particularly well when you're in an OS inside an OS) - it's certainly not a problem in Linux or on a Mac. But interested to hear if anyone else has experienced the same issue on Windows:

Deformed ball

Epic Amazon Fail

22 Mar, 2017

Frankly this is bizarre, but if you're looking for Python for Kids, I suggest you don't buy on Amazon for the moment:

Expensive!! (small image)

Much as I'd like to be getting a cut of that price, I somehow doubt I'm getting anything -- and you're possibly getting a poor quality knock off, going by this:

(Some more discussion on Hacker News here: )

Barnes and Noble looks to be a safer option - and you can still buy directly from No Starch Press of course.

Further update: "Amazon's Tepid Response to Counterfeiters Frustrates Sellers"

Breaking out of loops

30 Jan, 2021

Sherry W writes (excerpted):

Excellent book so far for my grandson.

On page 78 should it read?:

while True:
    lots of code here
    lots of code here
    lots of code here
    if some value == False

Book is written very well for that age group. It’s great to have a book that is able to explain concepts with simple examples.

The example on page 78 is not supposed to be executable code (obviously the text "lots of code here" repeated 3 times isn't), so it doesn't actually matter if the condition is "some_value == False" or "some_value == True". If I was going to write a runnable version of the example, it might look something like this:

some_value = True
while True:
    if some_value == True:

Which, if it was run, would print the following just once:


But you could use True or False in the above example (on the first line and the second-to-last line), and it would work just as well.

However a shortcut, not mentioned in the book (because I think simplicity and clarity is better for beginners), is that when you're checking for True, you can omit the "== True" altogether:

some_value = True
while True:
    if some_value:

Tkinter colorchooser problems (revisited)

23 Jul, 2020

Suranga writes:

My son and I have been learning Python with your great book. Unfortunately, we hit an issue with Colorchooser - the problem appears identical to this one: In the solution, you suggest we revisit Chapter 1 but can see no mention of a way to ensure IDLE is launched with No Subprocesses. Have we missed something here? Perhaps there was an earlier version of the book that did not contain this? (ours is the Tenth Printing). Thanks for any guidance you can provide!

No, you haven't missed anything. In subsequent printings of the book, my advice about using "No subprocess" has been removed -- that mode is no longer valid with the versions of Python 3 released since Python for Kids came out in 2012.

Interestingly, despite the fact all the code in the original print was tested by multiple people (including me!), I can't now find a version of python where from tkinter import * actually results in colorchooser.askcolor() working properly. So in yet later printings (some time after Jan 2017), I changed the instructions to reflect that fact that colorchooser is not imported by default when using import *.

This is now the corrected code:

from tkinter import *
from tkinter import colorchooser
tk = Tk()

Problem with bouncing ball

30 May, 2020

Lennier M writes:

I am on page 202 of your book, but when I followed your instructions, the ball stopped moving, instead of moving in multiple directions. Here is my code:

class Ball:
    def __init__(self, canvas, color):
        self.canvas = canvas = canvas.create_oval(10, 10, 25, 25, fill=color)

        self.canvas.move(, 245, 100)

        starts = [-3, -2, -1, 1, 2, 3, ]

        self.x = starts[0]
        self.y = -3
        self.canvas_width = self.canvas.winfo_width
        self.canvas_height = self.canvas.winfo_height()

    def draw(self):
        self.canvas.move(, self.x, self.y)

        pos = self.canvas.coords(

        if pos[1] <= 0:
            self.y = 1
        if pos[3] >= self.canvas_height:
            self.y = -1
        if pos[0] <= 0:
            self.x = 3
        if pos[2] >= self.canvas_width:
            self.x = -3

please help

If I run your code I get the following error:

Traceback (most recent call last):
  File "", line 40, in <module>
  File "", line 26, in draw
    if pos[2] >= self.canvas_width:
TypeError: '>=' not supported between instances of 'float' and 'method'

So that tells us the line which is failing, but why?

If you look at these two lines, hopefully you'll see the difference (and the reason for your problem):

        self.canvas_width = self.canvas.winfo_width
        self.canvas_height = self.canvas.winfo_height()

The missing brackets on the first line mean that you haven't actually called the winfo_width function (or method). So self.canvas_width isn't a number of pixels - it's actually a reference to the function itself. If we added a print statement at that point in the code it would be even more obvious...

<bound method Misc.winfo_width of <tkinter.Canvas object .!canvas>>

This is the reason why comparing pos[2] (which is a number - to be exact it's a floating point number) with self.canvas_width (which is the reference to a function/method) comes back with the error message: "'>=' not supported between instances of 'float' and 'method'".

If you add the missing brackets, you'll hopefully find the ball moves as expected.

Long and short dashes

14 Apr, 2020

Jan vK writes:

here's an example from your book that gives an error:
count_down_by_twos = list(range(40, 10, −2))
SyntaxError: invalid character in identifier
please inform me how to solve this problem

It looks like you might have copied-and-pasted the code? Perhaps from the digital version of the book? It looks like the -2 in your example is actually a hyphen (i.e. a long dash −) instead of a minus (i.e. a short dash -). So if I try the version of the code you sent, I get the same error:

>>> count_down_by_twos = list(range(40, 10, −2))
  File "<stdin>", line 1
    count_down_by_twos = list(range(40, 10, −2))
SyntaxError: invalid character in identifier

However, if I try with the correct character, there's no error:

>>> count_down_by_twos = list(range(40, 10, -2))

The next question you might ask is what does "invalid character in identifier" actually mean? An identifier is the name of something (the name of a keyword, a variable, a function or a class, and so on) -- valid identifiers are a sequence of letters (characters), digits and underscores. In effect you're getting that error message because python doesn't recognise "−2" (a long dash followed by 2) as any recognisable keyword, or variable, or anything resembling a valid identifier.

Hope that helps.

Two years of effort

11 Dec, 2012

Python for Kids in box My author copies arrived from No Starch today - the culmination of two years of not-an-inconsequential amount of effort.

If you happen to have ordered a copy, here's hoping it arrives in time to stuff the Christmas stocking.

New Programming Puzzle

09 Dec, 2012

puzzle imageA new programming puzzle has been added today. This one is a bit more difficult than the last - the actual solution isn't all that complicated, but it does require a bit of lateral thinking.

PfK and Python 2

11 Jul, 2016

Tara P writes:

I am going to be teaching Python 2 this coming school year and I am looking for a supplemental learning tool and projects for myself and my students. Will your book Python for Kids work with Python 2?

I saw that it is recommended to use Python 3 however the curriculum I am teaching we are to use Python 2. I am not familiar enough with Python to know if the code language is different enough between them where your book will not be useful for me?

The short answer is no, it is not really designed to work with Python 2. The longer answer is that most of the code samples will work, but there are subtle differences between the two versions that may make it a little more difficult to get things working properly. There are some obvious differences (such as the tkinter module being called Tkinter in Python 2), which are straightforward to deal with and explain, but the more complicated the code, the more likely you are to hit issues that are less obvious, and as a consequence, cause frustrating errors for your students (I'm thinking more of the games in the later chapters, which aren't tested with Python2, and may either fail or hang).

While moving from Python 2 to 3 is not enormously difficult, it's not necessarily something I would recommend for learners coming to a programming language for the first time.

Python 3 on Ubuntu 16

10 Dec, 2016

Roxana T writes (excerpted):

I did look at the installation instructions in ch1 but still didn't work. I'm using Ubuntu and the built-in (is this the right word?) Python Version. It is I guess 2.7. I have the 3 version too, but I have to set it as default probably because when I launch Idle I always get Python 2.7.

Since I wrote Python for Kids, Ubuntu has changed their software installer and, at least in Ubuntu 16.04 when I try, I don't see a package installer for Idle (even though there used to be one available). So the best thing to do is to install it from the command line, by opening the Terminal and running:

sudo apt-get install idle3

(You'll need to enter the administrator password). You should see something similar to the following:

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  fonts-opensymbol fonts-stix libboost-date-time1.58.0
  libboost-iostreams1.58.0 libclucene-contribs1v5 libclucene-core1v5
  libcmis-0.5-5v5 libcolamd2.9.1 libeot0 libetonyek-0.1-1 libexttextcat-2.0-0
  libexttextcat-data liblangtag-common liblangtag1 libmhash2 libmwaw-0.3-3
  libmythes-1.2-0 libneon27-gnutls libodfgen-0.1-1 liborcus-0.10-0v5
  libraptor2-0 librasqal3 librdf0 librevenge-0.0-0 libsuitesparseconfig4.4.6
  libwps-0.4-4 libyajl2 lp-solve uno-libs3 ure
Use 'apt autoremove' to remove them.
The following additional packages will be installed:
  blt idle-python3.5 python3-tk tk8.6-blt2.5
Suggested packages:
  blt-demo tix python3-tk-dbg
The following NEW packages will be installed
  blt idle-python3.5 idle3 python3-tk tk8.6-blt2.5
0 to upgrade, 5 to newly install, 0 to remove and 1 not to upgrade.
Need to get 647 kB of archives.
After this operation, 2,345 kB of additional disk space will be used.
Do you want to continue? [Y/n]

Hit Y to continue, and after installation, you should be able to run idle3 from the Terminal; and then, you won't get the funny compatibility errors you're been hitting with Python2. I also see Idle for Python 3.5 available from the launcher after installation, so you don't necessarily need to use the Terminal after that, if you don't want to.

idle in the launcher

Text position in tkinter

08 Dec, 2016

Drew M writes:

I have a question I am sure I don't know :) In tkinter I am creating a game and can't figure out how to set dimensions for text. I need it on the middle. My canvas is 1000 by 1000 so I divided in half. Which is of course 500. Now again, my question is how to put it there.

Adding text to a canvas is straightforward (similar to adding any other item, such as a line, or a rectangle). You say "middle" and not "center", so I assume you don't want the text directly in the center of the canvas? I've defined a smaller canvas here, but the principle is the same:

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=100, height=100, bd=0, highlightthickness=0)
canvas.create_text(50, 50, text='text')

text position center

So if you don't want the center, I'm guessing your problem is that this code...

from tkinter import *
tk = Tk()
canvas = Canvas(tk, width=100, height=100, bd=0, highlightthickness=0)
canvas.create_text(50, 0, text='text')

...(with coordinates of 50, 0) results in partially obscured text:

text position middle

The answer, is to use the named parameter anchor in the create_text function:

canvas.create_text(50, 0, text='text', anchor=N)

The anchor parameter controls the positioning of an item in terms of its coordinates. The default value is CENTER (so using this puts the center of the text at the coordinates (50, 0) in the earlier example), but you can also use NW, N, NE (effectively top-left, top-middle, top-right), W, E (left and right), and SW, S, SE (bottom-left, bottom-middle, bottom-right). So N puts the top and middle point of the text at the coordinates (50, 0), like so:

text position N

I hope that helps.

A parameter called evt

26 Jan, 2016

Dudley B writes:

I'm a Business Analyst trying to learn how to code. Luckily there's Python, a suitable language for absolute beginners like me. Thank God also for your book, Python for Kids. It's a great book which explains Python fundamentals in a fun and easy way. In Chapter 14 of the book, page 208, there is a parameter called "evt":

def turn_left(self, evt):     self.x = -2 def turn_right(self, evt):     self.x = 2

I can't figure out what this parameter is for, and why it's there since there is no value passed on to it. Please help me understand why "evt" is needed for those functions.

The evt parameter isn't brilliantly explained in that chapter, now that I look back at it. If you go back to the section titled "Making an object React to something" in Chapter 12, there's a description there of event bindings. The function described takes a parameter called event. After you've "told" tkinter about the function (that's the binding part), when an event occurs (such as the mouse being moved, or keyboard being pressed) it calls that function with an object containing more information (such as what sort of event it was).

The parameter evt on page 208, is simply a shortened name for the parameter event mentioned in the earlier chapter. In fact, the name isn't important at all -- you could even call it bob, or aardvark, or anything else you like.

By the way, another way of thinking about the tkinter event binding is that it's like a contract between two people. Let's say between a surfer, and an old man living on a cliff above the sea. The surfer says to the old man, "send me a message and let me know how high the surf is, whenever it changes". The function is that contract, and the message about the surf is the parameter value.

Hopefully that helps.

Stick figure error

03 Jan, 2016

WangXin writes (excerpted):

I got a confusing error from the Python 3.4 (command line - 64 bit), it shows me this: "NameError: name 'collided_left is not defined'" , I have checked my code over and over again and I can't find the error. Could you help me to check my code when convenient?

These sort of errors are (luckily) fairly easy to figure out. Any time you see an error about something not being defined (and you're sure you've got the spelling correct) you can usually trace it back to a mistake in how you have indented your code.

Here's a relevant example from the book:

indentation example (small image)

In this code, you can see that "class Coords" and "def within_x" have the same indentation (they're both at the left margin). Now if we look at the code you've entered, with visible whitespace, you can hopefully see the difference:

incorrect indentation (small image)

Your within_x, within_y and collided_ functions are all indented to the same level as the __init__ function of the Coords class -- in short, Python looks at them and thinks: "those are indented the same as the init for the class, therefore they must be member functions of the same class".

So, if you fix the indentation, I think you'll find your code suddenly works as expected:

indentation corrected (small image)


21 Feb, 2016

Kishore writes:

I bought this great book "python for kids". I want to give it as a gift to kid in India. She doesn't have internet, but has a computer. What do I need to download and give in a pendrive, so that she can finish the book without an internet connection.

Apart from the book itself, there's two extras to download: 1 - the solutions to all the programming challenges at the end of each chapter, and 2 - the code samples in the book (in case she has difficulty getting something to work).

The solutions are available from the publishers website here: A zip file of all the code can be found here: /python-for-kids/

Depending on when you purchased the book, you might also want to take a copy of the eratta. If it's a fairly recent reprint, there's no need. If the printing is before April 2015, then you should probably send that to her as well.

You didn't mention whether she already has Python installed, so if not, I suggest reading the first chapter yourself, so that you can include the right installation files for her OS.

Python on Chromebook

01 Mar, 2016

Cynthia B writes:

I purchased your book Python for Kids so that my 11 year old daughter and I could start to learn code together. We are trying to install Python on her (lenovo 100S) chromebook to no avail.

We followed several prompts and purchased a python shell which has been installed but can not figure out where to go from here, or if this will even be possible. Any advice?

As far as I'm aware, the Python shell extensions available in the Chrome OS store aren't Python 3 compatible - so at least from a version perspective, that's a non-starter. Even if the version was correct, I suspect your mileage would probably vary with some of the later code examples in the book, using that sort of environment (not a fully fledged installation... again AFAIA).

I don't have a Chromebook to try it out myself, but from a bit of searching, it looks like you can dual-boot Linux, and after that should be able to install anything you like ( - although Samsung-specific, I would hope the basic idea still applies).

I've found some instructions on doing so at the following sites:

Python3.5 on macOS

11 Jun, 2016

If you're installing Python3.5 on macOS, you don't need to follow the Automator instructions in Python for Kids any more. After installation, it's as simple as searching for IDLE in Spotlight (the magnifying glass in the top righthand side of the menu bar) and double-clicking on (usually) the top hit ("IDLE - Python 3.5").

You might still get an error message saying something like:

The version of Tcl/Tk (8.5.9) in use may be unstable. Visit for current information

Tcl is a simple programming language and Tk is (sort of) a graphics library (more info here -- the Tk graphics library is heavily used in later chapters of the book. If you happen to get the above error message, follow the instructions on the website to install the correct version of ActiveTcl for the version of macOS you're running. This post may also be of help.

String formatting

22 Jul, 2019

Lou O writes:

Hi Jason, Read a few good reviews of your book on Amazon.
One of the reviews pointed out "The explanation of String formatting needs to be updated. We don't do embedded values using %s anymore. I recommend skipping the chapters on Turtle Graphics and tkinter. The introductory chapter on classes and objects is not bad, but the topic is beyond what most kids will need, and they should really focus on imperative / procedural programming first using just lists and dictionaries as their basic data structures."
And I was wondering if those points had been taken into account and updated since then.

In terms of string formatting, the reviewer is correct but, on the other hand, % formatting hasn't actually been deprecated yet. From the official Python 3 documentation:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

I have thought about updating the section on formatting though, just because using str.format is the more accepted/modern method -- but this will probably have to wait for a second edition, or perhaps the next major reprint.

In terms of classes and objects, I don't agree at all. When originally writing the book, I thought rather hard about whether it was worth going into the complexity of that topic and, in the end, came to the conclusion that there is too much in Python which is object-oriented, and would be more confusing to explain without at least covering the basics (IMHO).

And finally, in regard to the comment about skipping the chapters on turtle and tkinter... sure, if they want a dry book on programming fundamentals, with nothing fun for a kid to experiment with -- one that they will then put down 10 minutes after opening and never return to -- by all means, skip those chapters.

For everyone else: will your child use the turtle and/or tkinter modules in the future? Probably not. But are they a useful tool to learn how to use those fundamental programming concepts (without needing to install any complicated third party libraries)? Personally, I believe so.

Bouncing in Polski

08 May, 2019

Marzena writes:

I'm writing to you because neither me nor my 11-year old daughter with whom we're learning Python can figure out where the problem is. We get the following error:
 ================ RESTART: C:/Users/Enarpol/Desktop/ ================
 Traceback (most recent call last):
   File "C:/Users/Enarpol/Desktop/", line 5, in <module>
     class Piłka:
   File "C:/Users/Enarpol/Desktop/", line 20, in Piłka
     if pozycja[1] <= 0:
 NameError: name 'pozycja' is not defined
And the code is exactly like in the book (some words are in Polish, but I assume it's not a problem for you to trace the error despite of it)

Your problem problem is caused by indentation and the idea of "scope" - I guess you're using the Polish language version of the book, so I'm not sure of the correct page number, but in the English language version of the book the section on Variables and Scope (page 84) would be useful to re-read.

In short, here is the incorrect bit of your code:

    def rysuj(self):
        self.płótno.move(, self.x, self.y)
        pozycja = self.płótno.coords(
    if pozycja[1] <= 0:
        self.y = 3

If I re-indent this with visible spaces, to show how it should look, hopefully you can see what you need to fix in the rest of your code:

    def rysuj(self):
        self.płótno.move(, self.x, self.y)
        pozycja = self.płótno.coords(
    ␣␣␣␣if pozycja[1] <= 0:
    ␣␣␣␣    self.y = 3

Why does this make a difference? Because in the case of rysuj above, the variable pozycja is only visible within the function - or to be exact, within the block of code that makes up the function. And how do we create a block of code? Basically through indentation. Your if statement was at the same indentation level as def rysuj(self), so it wasn't part of the function and that's why you're getting the error name 'pozycja' is not defined.

Hope that helps.

Stickman Moves

31 Jan, 2019

Alex Z writes (edited):

I'm playing with the last chapter game, cf. the file. I'm a little confused about how the key presses are expected to cause the character [to] move.

If the player hits the right or left key, the character starts moving but keeps moving and doesn't stop unless [colliding] against a wall or a platform. Even jumping on a platform doesn't cause the stick figure to stop. This makes hard to climb to the top parts of the area. Is it the expected behavior of the game ?

I am not the first to experience this problem, see the folowing message on stackoverflow: How to move character only when key is pressed down Python

Yes, that is the expected behaviour of the game. The point is to make it more difficult to reach the top platform, so once the character starts running he doesn't stop, unless he collides with something. However, if you do want to change it so that the character only moves when the key is held down, there's a few fairly minor modifications you can make (which are discussed in that stack overflow article):

i. Add a new function to stop the character moving, by changing the value of the x variable to 0. So in the StickFigureSprite sprite class we add this new function:

class StickFigureSprite(Sprite):
    def stop_moving(self, evt):
        self.x = 0

ii. Now we need a way to call the new function. So we add two new key bindings to the __init__ function of the same class, and set the starting value of the x variable to 0 (it's currently set to -2 so that the stick figure starts running as soon as the game starts):

class StickFigureSprite(Sprite):
    def __init__(self, game):
        self.x = 0
        game.canvas.bind_all('<KeyRelease-Left>', self.stop_moving)
        game.canvas.bind_all('<KeyRelease-Right>', self.stop_moving)

So with these changes the game starts and the stick man won't move. When you hold the left or right key down, the x variable is set to -2 or 2 respectively which starts "him" moving. When you release the key, it sets the value back to 0, which stops him moving again.

You might notice one slight problem when running the game after this change - the stickman starts quickly and then slows down. This is caused by the keyboard repeating which then impacts the performance of the mainloop function in the Game class. This is an unfortunate side effect of the way the code for the game is written (the stickman code is not the standard way to handle animation with tkinter -- however it was written this way to hopefully make animation concepts, in programming, slightly easier for a child to understand).

iPad Pro and Pythonista

26 Jan, 2019

Lucia C writes:

I am currently reading your book but do not have access to a computer. I do however have my Ipad pro.

There is an app available called Pythonista 3, are you familiar with this app and would you recomend it to follow your book?

Unfortunately, Pythonista has it's own custom UI library, so I don't believe it supports turtle or tkinter -- the latter chapters of the book rely heavily on tkinter for graphics in the games. Without this you're going to struggle completing all the examples.

If you only have an iPad, a cheap option might be to purchase a Raspberry Pi (at time of writing a Pi starter kit is UK£51.99/US$79.99) and use that for your programming activities. While you'll initially need a monitor as well, if you want to stick with the iPad, it looks like it is possible to connect from the iPad to the Pi (so your iPad effectively becomes the monitor) using VNC -- more info can be found here in this instructables article.

Hope that helps.

PFK and iPython

27 Jan, 2019

Jobakhan writes (edited):

Using this code
import sys
def moon_weight():
    print('Please enter your current Earth weight')
    weight = float(sys.stdin.readline())
    print('Please enter the amount your weight might increase each year')
    increase = float(sys.stdin.readline())
    print('Please enter the number of years')
    years = int(sys.stdin.readline())
    years = years + 1
    for year in range(1, years):
        weight = weight + increase
        moon_weight = weight * 0.165
        print('Year %s is %s' % (years , moon_weight))

then it gives me this:
error in ipython

Why is this happening?

It looks like you're using iPython/Jupyter Notebook to run the examples in the book. Python for Kids wasn't specifically written to work with iPython (nor was the code actually tested with that app), which is why you're having issues. Having said that, I think many of the examples will work, but some, like the code you sent, will need modification.

In the case of the moon_weight function, it's using sys.stdin.readline() (that's the sys module, "standard input" object, readline function) to read input from the user running the program. There are a couple of ways to read command line input in Python - and in the case of Jupyter it looks like stdin doesn't behave the same way as the Python shell. I found the following in the Jupyter client documentation:

This pattern of requesting user input is quite different from how stdin works at a lower level. The Jupyter protocol does not support everything code running in a terminal can do with stdin...

So what's actually happening when you run that code? The function sys.stdin.readline() returns straight away with an empty string (''), and Python then throws an error when trying to convert that empty string to a floating point number. If you replace sys.stdin.readline() in the above code with input(), the program should then work in jupyter:

weight = float(input())
increase = float(input())
years = int(input())

Traditional Chinese

16 Mar, 2019

你 好!

traditional chinese translation cover

Available from Wu Nan Books.

Not the normal knock-off

02 Aug, 2019

Usually on Amazon, we see Python for Kids knock-offs which are an exact copy of the book, with cruddy printing and/or binding. No Starch have a clever binding which allows books to open flat, without falling apart after reading a couple of chapters (clever enough that a few people thought it was actually a failure in the glue) - so these were pretty obviously cheap copies, even without the often misprinted and missing pages.

However, an eagle-eyed reader recently notified No Starch of a new type of knock-off -- where they have slightly rewritten the text (I assume just enough to fool a copyright-checking algorithm), and included content from (I think) other sources, to make it even less likely that any automation would flag the book.

For example, here's an excerpt from Python for Kids...

pfk excerpt 1

And here's the dodgy knock off...

knockoff excerpt 1

Erm... what the heck is a "Trump String"?

Here's another one from PfK:

pfk excerpt 2

And here's the knock off again...

knockoff excerpt 2

Yeah... way to rewrite it to be more boooooooring, Book Pirates!

The code examples are pretty much exactly the same in the knock-off (at least the examples I checked) - if badly formatted (including misprinted wingdings characters and other artifacts).

So, the first part of the book is basically a slightly (and extremely poorly) rewritten knock-off of mine. The second part of the book has things like bubble sort, insertion sort and...

knockoff pagerank

...because every self-respecting kid needs to how to write a sorting algorithm (by just looking at the code) and how to use numpy and pandas for page-rank???

And from there, on to games like Hangman, but written with Python2 and incorrectly formatted as well...

knockoff hangman

A garbage knock-off, and 29 five-star reviews in a couple of weeks, no less (I assume paid for). Interestingly, I clicked through a few of the other reviews by those same reviewers and found more poorly written texts. It's an Amazonian (sic) nest of crappy Python books!

Tick tick tick. I wonder how long it'll take Amazon to catch on...

IDLE3 on Ubuntu

07 Sep, 2019

Chris K writes (excerpted):

I'm teaching myself and home educating my three young daughters at the same time. Just a little bit every day (excepting Sunday which is entirely reserved for pancakes and not inter-computery-things) . Thank you for providing the opportunity for me to introduce the subject of computer programming in a fun way.
Anyhow, we hit a snag early on that does not seem to get a mention on the publishers site or your blog. When instructed to search for IDLE on the Ubuntu software centre nothing of relevance was listed. I had one of the girls do it and she was very disappointed...
...I've done some homework and followed instructions on installing idle3, which worked. So we are all set to go today.

I don't know how useful this feedback is to you but this is an opportunity to express my appreciation for all your hard work and skill, so I'm taking it.

The next re-print of Python for Kids will include updated instructions for installing IDLE3 on Ubuntu - which obviously doesn't help anyone reading the current print of the book. My steps are pretty similar to the link you've referenced:

snippet from the book

Thanks for the email - it's a good prompting to put something on my site, which others in the same position might come across.

Problems with restarting the game

22 Sep, 2019

Serhii writes (excerpted from two emails):

I teach programming lessons for the pupils. We try to do restart button for the "Bounce" as it follows:
...there is a problem in "command=restart".

If I run your code I get the following error:

Traceback (most recent call last):
  File "", line 105, in <module>
  File "", line 86, in add_restart
    self.restart_button = Button(tk, text="Click to Restart Game", command=restart, bg="green")
NameError: name 'restart' is not defined

Looking at your code...

    def add_restart(self):
        self.restart_button = Button(tk, text="Click to Restart Game", command=restart, bg="green")

...the problem is you don't actually have a function called restart anywhere - which explains the error message "name 'restart' is not defined". The easiest way to fix this, is to define that function inside your Game class, in which case the above function should actually be:

    def add_restart(self):
        self.restart_button = Button(tk, text="Click to Restart Game", command=self.restart, bg="green")

(note the addition of self there)

The restart function itself should remove the restart button from the screen, move the paddle and ball back to the starting position, and reset the score. I suggest you create a simple function first, just to prove the button works:

    def restart(self):
        print("Restart the game!")

If you see "Restart the game!" printed when clicking the button, you know you're good to start adding the code to do the actual restart (you might also find this post useful: journal/2018/03/04/restarting-the-bounce-game-revisited). The other thing you might want to think about changing, is to only add the restart button if the game is over (so that's a small change to the while loop at the bottom).

Hope that helps.

Trouble with Automator

28 Jul, 2014

Jean-Jacques B writes:

I am trying to set up my iMac for the book, having trouble with the automator script:

open -a "Applications/Python 3.2/" --args -n

Run Shell Script failed open: unrecognized option '--args'

I can get python to launch the other ways, but then turtle doesn't work.

This had me stumped for a moment (couldn't find any similar errors when I googled).

It actually looks like a poorly handled error in the Automator. If you copy+paste what you entered into the Terminal, you get an entirely different error message:

$ open -a "Applications/Python 3.2/" --args -n
Unable to find application named 'Applications/Python 3.2/'

Which hopefully helps you figure out where you went wrong... try adding a / (slash) in front of the path to IDLE. eg.:

open -a "/Applications/Python 3.2/" --args -n

Incrementing photo filenames

28 Dec, 2014

Emmeline writes:

I'm twelve and I recently got a raspberry Pi camera module. I really wanted to do stop animation with it but, when I used Tkinter to make a button it would take a picture when I pressed it and save it as I specified. The problem is if I wanted to use the button again it deleted the old image ex image.jpg and replaced it with a new image (image.jpg). Do you have any suggestions of how to change the code so it will name the photos numerically. Ex image1.jpg then image2.jpg. I'm doing all this in idle3. Thanks a lot for the book. "Python for kids" is great.

Glad you like the book.

There's a few ways you can change your code to have an incrementing filename. You could write a class, which uses a variable to store the current number. The class would have a function which increments the variable and returns the value. Something like this would work:

>>> class Counter:
...     def __init__(self):
...         self.counter = 0
...     def next(self):
...         self.counter += 1
...         return self.counter

You could use the class by creating an object like this:

>>> c = Counter()

You could then create a function to return a unique image name each time it's called:

c = Counter()

def get_image_name():
    return 'image%s.jpg' %

You could also just adapt the code above to create a class which returns unique image names:

>>> class ImageNames:
...     def __init__(self):
...         self.counter = 0
...     def next_image_name(self):
...         self.counter += 1
...         return 'image%s.jpg' % self.counter
>>> im = ImageNames()
>>> im.next_image_name()
>>> im.next_image_name()

By the way, you can find more about embedding values in strings in Chapter 3, and classes and objects in Chapter in Chapter 8.

Hope that helps.

Intermediate Python Resources

19 May, 2014

Jim G writes:

I'm currently going through your book python for kids. I was wondering what books or other sources you recommend for learning more about python

Well, there are a heap of online tutorials, and dead-tree, printed books to choose from. However, I have an alternate suggestion to further reading.

Once you've learned the basics, why not pick a project? Find something you want to create - whether that's a game, a desktop application, a website or something else - make sure you have the Python documentation bookmarked, and a search engine to hand, and start working on it. You can't beat actually coding for improving your knowledge and ability.

Let's say you decide to write a program to send a message from one computer to another, on your home network. That might lead you to the socket module in the Python modules documentation. Assuming you find that too opaque, you might search for a "python networking tutorial" or perhaps a "simple python socket example" - but either way, the investigation, and putting that information to work in a program of your own will be a much more valuable learning experience than just reading a dry chapter about networking in some resource.

Questions and remarks on Python for Kids

20 May, 2014

Marcin S writes:

I am currently testing your book on my girlfriend who is not a kid anymore but a person that has not written any code in her entire life. To assist her better I have read the whole book. I think I spent my money well when I bought it.

Still, I have some questions and remarks.

Did you consider to emphasize more we are using Python 3 in the entire book? I know that the reader is instructed to download that version, but if someone uses Python 2 for some reason (e.g. computer science classroom with outdated software), one will get different results. In the context of your book I have found two important cases: 1) division always produces a float in Python3 because we no longer have a strict difference between integers and floats, 2) input() works like raw_input() from Python2, while input() in Python2 made implicit eval(). [1]

The errata mentions input() behaves differently than readline() depending on the context -- console or shell. I am unable to replicate it. BTW, the parameter to read()/readline() specifies the maximum number of characters to read, not the exact number. And there is one more thing -- if one reads less characters than available on stdin, remaining characters will be read on the next call to read()/readline(). [2]

Are strings enclosed in triple double-quotes omitted as reserved for documentation? I think only triple single-quotes are mentioned in the book. [3]

Why did you choose to name classes with plural names (class Giraffes) instead of singular (class Giraffe)? [4]

The "is" keyword is mentioned in the keywords section as a complicated concept and is omitted in the examples. I have one remark on that: PEP8 suggests using "is" when checking if something is None (not with "=="). [5]

I have seen range() with 3 arguments mentioned later in the book. Did you consider mentioning slices ([a:b:c]) as well? [6]

Did you consider mentioning "for" and "while" with the optional "else" block? [6]

The book mentions random.choice() but the bounce game uses shuffle() and picking by index instead. [7]

Mr. Stick Man checks for collisions using comparisons glued with "and". Did you consider constructs like "x1 < x < x2" instead of "x1 < x and x < x2"? [8]

Why did you choose a Tk construct based on sequence: update_idletasks(), update(), sleep() instead of mainloop() with rescheduling with Tk.after()? There would not be any active wait then and it would be event-driven. Is not the update_idletasks() included in update()? [9]

I've annotated your comments so I can address each in turn, but the answer to many of your points is somewhat similar:

[1] No, at the time of writing, I didn't consider more emphasis was needed, other than what is detailed in the first chapter. But as time has gone on, the differences between 2 and 3 account for a significantly large percentage of the questions I get about the book, so perhaps something additional makes sense. [2] The problem is reproducible in Python3.2 (and older versions). In 3.3 onwards, the max characters parameter works as expected. [3] No, the triple double-quotes were omitted essentially for simplification reasons. To make it less confusing for younger readers. [4] I chose plural class names mainly to try to indicate class as a kind of grouping - trying to distinguish between that and singular object instances. Yes, not particularly standard, but I had a (possibly vain) hope it would help to highlight the difference between class and object. [5] "is" was omitted again for simplification reasons -- to avoid a complicated description of how object identity works. [6] Again, slices and else blocks in for/while loops were omitted for simplification. [7] You'll find a description of the shuffle function on page 136. [8] Another one omitted to simplify things. Combining conditions with and and or is, I believe, more straightforward for kids to understand (even if x < y < z is a bit cleaner) [9] This one came up in the review from one of the technical proof readers. mainloop is definitely the better (read as correct) approach, but I wanted to stick with a loop and update/update_idletasks because it made it obvious, to the reader, what is happening. Each loop tells one of the objects to do something (move and draw), and then triggers Tk to redraw the screen (the reason for using both update and update_idletasks is that when writing the book -- with an earlier version of Python3 -- I saw some animation jittering when using only the one call. Using both seemed to resolve that issue. Perhaps I should've checked why at the time, and maybe it's no longer an problem with Python3.4)

Hope that helps clarify some of your questions...

Python on the iPad?

10 Mar, 2014

Beth S writes:

I teach gifted elementary-aged students in Albuquerque, NM. A few of my students and I have been working through your book. We have limited desktops in our classroom, but we also have access to several iPads. In researching the various apps _available, I’ve realized that most (if not all?) do not include the tkinter module. To be honest, I’m rather new to programming myself!

Do you have a recommendation for an iPad app that would be appropriate for students using your book?

Thank you for your time and your ability to clearly explain the basics of Python!

I'm afraid I don't know of any way to use an iPad for Python, other than by jail-breaking the device (and even then I have no idea whether tkinter would work anyway - I think unlikely).

The only thought I had was whether you could use the desktop PCs in your class to run multiple VMs (using something like VirtualBox) and then connect to those using a Remote Desktop App for the iPad. Not straightforward to set up, but it might accomplish what you want (assuming the desktops are reasonably powerful of course).

Sorry I can't be much help there.

Update: since sending my initial reply, I came across this discussion, which explains why you're not likely to see tkinter on the iPad anytime soon.

Is The Animation Loop Necessary?

18 Aug, 2014

Christopher D writes:

I'm currently working through your book and enjoying it immensely. The following is baffling me though, so hoping you can help.

In Chapter 13, page 197 (after creating the ball object), you wrote: "If you run this program now using Run>Module, the canvas will appear for a split second and then vanish". You then go on to write about how its necessary to add the animation loop to stop this happening.

My window appears and draws the ball correctly, but does not vanish. Reading through the code I don't understand why it's expected to disappear either. This seems to be a key point so would be grateful if you could shed light! I'm running Python 3.4.1 by the way.

Thank you in advance for your help!

You've found an error in the book, I'm afraid. If you run the code using the Python console (try it by opening a command prompt, or terminal, and running python, the window will indeed appear and vanish. The basic idea is, there's nothing left for it to do, so no reason for the window to remain open. That's the reason for adding an animation loop of some kind (in the book I use a very basic while-loop, but tkinter also has a mainloop function for doing this). However, when you run the same code with Idle (the Python Shell), which is written using tkinter, the window remains open because there's already a main loop running (started by the Shell itself). So the book is both right and wrong, I guess, depending on how you want to run the code. The errata has been updated accordingly. Thanks for the "bug report".


29 Aug, 2014

Marta C writes:

I'm new in programming. I just want to know if it would be too hard or complicated to use Python 2.7 with the Python for Kids book? I am still practicing for a class I took with v 2.7. Can I have both IDLE 2.7 and 3 in the system and use them separately and not run into problems? Thank you.

Most of the examples in the book will work with Python 2.7 -- but some won't without modification (particularly anything using the tkinter module). And you may hit subtle problems which will be harder to figure out as a consequence. However, you can install both Python 2.7 and 3 on the same system (you didn't say, but I'm guessing you're using Windows -- after installation, you'll find you've got both c:\Python27 and c:\Python34 directories, assuming you install the latest Python version, on your hard drive) -- just make sure you select the correct directory when setting up the IDLE shortcut (described in Chapter 1).

Restarting the game

30 Aug, 2014

Lyna M writes (excerpted):

I bought your book Python for Kids with the intention to teach my son Python later on but have now been using it myself to learn Python as I find your book to be quite comprehensive even if it was 'for kids'.

I've been doing the Bounce tutorial and would like to find a way to add a restart button so that each time the game ends, the player can restart the game if they want to.

I've applied the codes for Game Over but would like to add a restart button after that.

if ball.hit_bottom == True:
    canvas.itemconfig(game_over_text, state='normal')
    btn = Button(tk, text="Click to Restart Game")

tk = Tk()
btn = Button(tk, text="Click to Restart Game")

How to tie in the button so that it restarts the game when clicked? I've been trying out codes from forums and blogs but they don't seem to work or are too hard to understand.

There's a few ways you can handle the restart. If you look at the programming puzzles in Chapter 14, the first challenge is to delay the game start using the <Button-1> binding; to tie a mouse button click to a function which then starts the game. You could adapt that function to also restart the game once it's over. That's probably the most seamless approach.

If you really want to use a button, you need a way to add it just once -- because where you've added it (inside the loop), you'll get one button added to the window for every iteration of the loop. After the loop finishes isn't really the right place either.

First of all you'll need a Game class which will tie all the game objects together. Basically the new class would have object variables to 'store' the paddle, the ball, the score, the game-over-text, and also your restart button (initially the restart button variable would be set to None). So rather than adding the button inside the if-statement, you might do something like this:

    game = Game(canvas, paddle, ball, score, game_over_text)

    --- ✂ ---

    while 1:

        --- ✂ ---

        if ball.hit_bottom == True:
            canvas.itemconfig(game_over_text, state='normal')
            if game.restart_button is None:

In the above code, we check if the value of the game variable restart_button is None (in other words, the button is not currently displayed), we call a function add_restart - so that fixes the problem of adding the button more than once. Here's the code for adding the button:

class Game:

    --- ✂ ---

    def add_restart(self):
        self.restart_button = Button(tk, text="Click to Restart Game", command=self.restart)

The command associated with the button is the function on our Game class called restart - this is the bit of code that takes care of hiding the "Game Over" text, putting the ball and paddle back in their starting positions, and so on.

Hope that helps somewhat.

Multiple statements found

09 Sep, 2014

Arijjan V writes (excerpted):

When I enter code into the compiler I continue to get multiple statement error messages. Even if I copy the code from the book.

I use Idle 34 on windows professional 7. This is what I typed into the Idle Shell.

found_coins = 20 magic_coins = 70 stolen_coins = 3 coins = found_coins for week in range(1, 53):     coins = coins + magic_coins - stolen_coins     print('Week %s = %s' % (week, coins)) **Click Enter** SyntaxError: multiple statements found while compiling a single statement

I searched online but it's not an indent error. I'd appreciate any help.

To be honest, I'm not quite sure how you managed to get that error when typing the code into IDLE - the only way I can get it to happen, is if I copy-and-paste directly into the Shell:

Multiple statements showing error

The reason being is that you can only copy-and-paste line-by-line into the Shell window (a quirk of the way it works). What you should actually be entering looks like this:

Multiple statements without error

If you want to paste in a large chunk of code, then click File, then New File, then paste the code, and save the file before trying to run it:

Multiple statements in new file

If you can reproduce the problem when typing in the code, send a screenshot (take it after entering a few lines) -- I'd be interested to see if it's obvious from the screenshot what the cause is...

Which format?

13 Jun, 2014

Koki Y writes:

I have a question. You use % for format instead .format(). In the python tutorial, it is written that % format is an older version of format. What's the point of using % format?

The book uses the % operator (also known as the interpolation operator) basically through omission more than anything else. The first electronic version was written for Python2 (back in 2006/2007), then updated to be compatible with both 2 and 3. While it was almost totally rewritten, to be published as "Python for Kids", some of the existing text was repurposed -- however, the string formatting section wasn't specifically updated for Python 3. I suspect that's somehing we should probably fix when/if it's reprinted again.

By all means, use the format function as detailed in the Python documentation.

Python 3.4 Shell

16 Jun, 2014

Kirk K writes:

On page 12 it says File>New Window but I cannot find it on our Windows version 3.4.1. Please advise.

It looks like, as of Python 3.4, they've changed the menu, so File->New Window has become File->New File (which makes the Shell consistent with other text editors, at least). It still has the same behaviour though - opening a new window for typing in your Python code.

Restart when running tkinter

14 Jun, 2014

Craig S writes:

My son is having a problem running the random rectangle program on page 174 of Python for Kids. He is using version 2.7.7, so the Tkinter module must be capitalized (just so you don't suggest to capitalize it). Every time he tries to run the module, it comes up with a new window saying, "RESTART". He tried to copy and paste your code, but came up with the same results. This is the code he's written. from Tkinter import * import random tk = Tk() canvas = Canvas(tk, width=400,height=400) def random_rectangle(width, height):     ... random_rectangle(400, 400)

This is what comes up when he runs it. Python 2.7.7 (default, Jun 1 2014, 14:17:13) on win32 Type "copyright", "credits" or "license()" for more information. >>> =============== RESTART ===============

Please share some advice. Thanks.

A couple of thoughts:

  1. He's missing the pack function after the 4th line of that code (canvas.pack())
  2. You're probably not running Idle in "No Subprocess" mode (see Chapter 1 of the book for setup instructions). If that doesn't work for you, for some reason, then best thing to do is use a text editor, save the code and then run it from the command prompt by typing python (see for instructions on running the command prompt if you're not aware how to do that)
  3. You may hit other weird issues if you're not using Python3, since all the code in the book was written and tested with 3.x. Much of it is probably fine, but no guarantees there...