askcolor

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 *
tk = Tk()
tk.update()
colorchooser.askcolor()

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

Update: 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.


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')
canvas.pack()
tk.update()

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')
canvas.pack()
tk.update()

...(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.


PfK and Python 2

10 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.


Python3.5 on macOS

10 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 http://www.python.org/download/mac/tcltk for current information

Tcl is a simple programming language and Tk is (sort of) a graphics library (more info here http://tldp.org/HOWTO/TclTk-HOWTO-3.html) -- 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 python.org website to install the correct version of ActiveTcl for the version of macOS you're running. This post may also be of help.


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 (http://stackoverflow.com/a/15261253/2685350 - although Samsung-specific, I would hope the basic idea still applies).

I've found some instructions on doing so at the following sites:
http://www.howtogeek.com/162120/how-to-install-ubuntu-linux-on-your-chromebook-with-crouton/
http://lifehacker.com/how-to-install-linux-on-a-chromebook-and-unlock-its-ful-509039343
http://www.linux.com/learn/tutorials/764181-how-to-install-linux-on-an-acer-c720-chromebook


Pendrive

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: http://nostarch.com/pythonforkids. A zip file of all the code can be found here: /python-for-kids/code.zip.

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.


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)


Tkinter mainloop issue on Raspberry Pi

26 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

21 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: https://bugs.python.org/issue24847).

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 myletter.py

14 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()
print()
print('Dear Sir')
(excerpted)

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.


Deprecated switch

12 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.


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.

if-statement

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).


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/IDLE.app" --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.


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()
>>> c.next()
1
>>> c.next()
2

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' % c.next()

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()
'image1.jpg'
>>> im.next_image_name()
'image2.jpg'

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.


Multiple statements found

08 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...


Restarting the game

29 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:
    time.sleep
    canvas.itemconfig(game_over_text, state='normal')
    btn = Button(tk, text="Click to Restart Game")
    btn.pack()
tk.update_idletasks()
tk.update()
time.sleep(0.01)

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

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 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:
            time.sleep(1)
            canvas.itemconfig(game_over_text, state='normal')###
            if game.restart_button is None:
                game.add_restart()

In the above code, if the game variable restart_button is None (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)
        self.restart_button.pack()

The command associated with the button is the function on our Game class called restart - this is the guy 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.


Co-existence

28 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).


Is The Animation Loop Necessary?

17 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 bounce.py), 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".


Trouble with Automator

27 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/IDLE.app" --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/IDLE.app" --args -n  
Unable to find application named 'Applications/Python 3.2/IDLE.app'

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/IDLE.app" --args -n

Python 3.4 Shell

15 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

13 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 yourscript.py (see http://windows.microsoft.com/en-us/windows/command-prompt-faq 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...

Which format?

12 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.


Questions and remarks on Python for Kids

19 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...


Intermediate Python Resources

18 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.


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.


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 python.org, and are getting this message when opening IDLE:

"WARNING: The version of Tcl/Tk (8.5.9) in use may be unstable. Visit http://www.python.org/download/mac/tcltk/ 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+, x8664/x86)" (file: ActiveTcl8.6.1.1.297588-macosx10.5-i386-x8664-threaded), 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 8.5.15.0. 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". ツ


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:

avery.forward(50)
Traceback (most recent call last):
   File "", line 1, in
     avery.forward(50)
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()

...you should have a bit more success.


Loop confusion

26 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
    print(i)
    for j in hugehairypants:    # LOOP 2
        print(j)
        for k in hugehairypants:    # LOOP 3
            print(k)

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
    print(i)
    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

19 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/IDLE.app" --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/IDLE.app" --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.


What is -n for

27 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.


Python Kinderleicht

30 Jul, 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 amazon.de (probably others, but those were the first couple of links that popped up).


Tkinter problems on the Raspberry Pi

09 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()

Scratch or Python?

23 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.


Problems installing Python

05 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... http://superuser.com/questions/168561/python-wont-install-on-windows-7... you should try disabling UAC. I'm not a home Windows user, but a quick google found this: http://www.howtogeek.com/howto/windows-vista/disable-user-account-control-uac-the-easy-way-on-windows-vista/. Hopefully that fixes the problem.


O'Reilly Media Discounts

04 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.


Lander Solution Posted

26 May, 2013

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


One versus two underscores

19 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/PaddleBall.py", 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:

14c14
<     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!


Problems with files

18 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

01 May, 2013

Michal writes:

My son has found a problem. It is regarding:

from tkinter import *
colorchooser.askcolor()

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

Traceback (most recent call last):
File "colorrect.py", line 2, in <module>
colorchooser.askcolor()
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:

colorchooser1

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

colorchooser2

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):

colorchooser3

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!


Python on the Web?

17 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.


Solution 6

14 Apr, 2013

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


Between Giants

03 Apr, 2013

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


Belated...

8 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 code.org 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.


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.


Puzzle Updates

12 Feb, 2013

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


The Front Page

31 Jan, 2013

raspberrypi.org Very cool. The front page of raspberrypi.org.

Officially geeked out.


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.


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.


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.


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. ツ


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 image A 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.