Archive for July, 2012

Python Tutorial Video


Simple tutorial on Fibonacci numbers.

This is my first ever video tutorial. It’s fairly simple (no, I didn’t use a recursive algorithm in this example).

I hope you enjoy it,



Here’s a version that uses recursion and had a GUI.

GUI Fibonacci Tutorial



A GUI Python Calculator


Click on image to download the code.

Python Calculator

Here’s a little calculator I wrote.

I’ve recently had a look at this and fixed the divide by zero bug.

The links now point to updated code on github.

It you want to look at the code and/try it out, just click on the picture. Or click here.

If you find any bugs, let me know.

Read on if you want to know how the code works.

The program begins by importing tkinter, to handle the GUI. Straight after that we set up a “class” called “Calc()”. In some of the programs we’ve looked at so far, we have been using pre-defined “classes” and, therefore, the Object Orientated approach to programming. What’s different this time is that we are creating a class from scratch.

The first “method” that we create for this class of objects is a “constructor”. This section of code is run automatically whenever and instance of “Calc() is create. The object has some variables associated with it. Total is a running total of the sums we have done so far – so we set it to zero initially. “self.current” is a string in which we hold the numbers that are being entered via the GUI. Then we have three “flags”. I’m not sure if this is the most effective way to do this, but it seems to work okay. The “new_num” flag is set to true if the calculator is expecting a new number (eg after the user has pressed “+” etc.) There’s also a flag for “op_pending” which tells if there is still a calculation to do. The flag “self.eq_flag” keeps a record of whether equals has just been pressed. I needed these flags to make the calculator work as expected. For instance, you can press “equals” when there is no operation pending, and the number will stay the same. You can press an operator after “equals” and that action will be done to the current total. Or you can start a new number after pressing equals and the previous target is discarded.

Each instance of the class I am creating will have these variables, and also some “methods”.  Methods look just like functions. This one controls how the calculator responds to a number being pressed. First it takes the text from the box. If the new_num flag is set to “True”, it ignores what was in the text box and starts a new number with the button-press. Of course it then sets the “new_num” flag to false, so that we can add more digits to this number.

If we are not looking for a new number, it will continue adding the digits we have pressed onto the “self_current” string (at this point we are treating whatever is input as a String). The method also checks that the used hasn’t tried to have 2 decimal point symbols. Only the first one will actually be accepted.

The method ends by deleting everything in the text-box and printing the “self_current” string out again.

Now we deal with the method that gets called when we press equals. This is a very simple method! If there is an operation pending (ie. a sum to do), then we do the sum. Otherwise, pressing equals has no effect

Next comes the “do_sum” method. This starts off by converting the string in “self.current” to a floating point number. It then does the operation that is stored in “self.op”, performing it on “” and “self.current”. Then it displays the result in the text box and sets the new_num flag to True.

This method defines what happens if one of the “operation” buttons on the calculator is pressed. If we have an operation “pending”, the we work that out first. Otherwise, we check that the total variable holds the correct total and set the op_pending and new_num flags to true, so that we are ready to find out which value the user wants this operation applied to.

The next three methods sort out some simple matters. The cancel, all_cancel and “+/-” buttons. As you can see, all_cancel is the same as cancel, but with the additional zeroing of And the plus / minus button just inverts the sign of whatever is in the text-box at that moment.

And that’s it for the workings of the calculator. The rest of the program just sets up the GUI. I am not going to spend too long on this, except to show you how I  made some of my buttons with a loop.


By the way, if you haven’t seen “lambda:” before, this is a really useful thing. Usually, when you specify a function in the command part of a button’s creation, you leave the brackets off. If you leave them on, the program will behave as if the button has been pressed, even when it has not! Lambda lets you get around this, which is of course essential if you want to pass some parameter to that function.

Here’s the loop that makes the buttons 1-9.





So first I created a little string with my numbers in the order they appear on the buttons on a number pad. Then I use j and k to iterate over all the positions in my grid in which I want a button. I use my version of the Button class which will allow me to use my built-in command-setting method.

I’m not going to write any more than that. You can download the code if you want to see the whole thing.

Please let me know if you spot any mistakes or ways to improve this.




Ryan Walmsley and his friends Ben, Edward and Luke are doing a coding marathon this weekend, creating a game using Python.



RPi Blog post.

This is such a cool idea. Can’t wait to see what they come up with.

Making Simple Games in Python


The Summer Holidays are almost here. The RPi foundation has announced its first programming competition. Let’s write some games!

You can download the code and sound files for this program here.

This program includes several features that are useful when making games. Try thinking of something you’d like to do in a game and then adapt the code to create the effect you want.

I haven’t managed to get WordPress to show the indentations correctly. I’d recommend downloading the file rather than trying to cut and paste!

# simple game program

# import the pygame library
import pygame

# initialise the game engine

# define colours
raspberry =  [135,  38,  87]
green     =  [152, 251, 152]
black     =  [  0,   0,   0]
blue      =  [  0,   0, 255]
red       =  [255,   0,   0]
yellow    =  [255, 255,   0]
colours = [blue, red, yellow, raspberry]

# set the height and width of the screen & title
size = [400, 300]
screen = pygame.display.set_mode(size)
screen_rect = screen.get_rect()

# create a surface to hold the “blob”
blob = pygame.Surface((40,40))
blob_rect = blob.get_rect() =
blob_col = 0

def change_blob(blob_col):
if blob_col == 3:
blob_col = 0
blob_col += 1,(colours[blob_col]), (20, 20), 20)
return blob_col

# draw initial blob, (colours[blob_col]), (20, 20), 20)

# initial speed = 0
x_speed = 0
y_speed = 0

# load sounds
wand  = pygame.mixer.Sound(“wand.wav”)
cow   = pygame.mixer.Sound(“cow_toy.wav”)
boing = pygame.mixer.Sound(“boing_x.wav”)
frog  = pygame.mixer.Sound(“frog.wav”)
horn  = pygame.mixer.Sound(“horn.wav”)
laser = pygame.mixer.Sound(“laser.wav”)
sounds = [wand, cow, boing, frog, horn, laser]
sound_num = 0

# give the window a title

# loop until the user clicks the close button
done = False

# create a timer to control how often the screen updates
clock = pygame.time.Clock()

# main game loop
while done==False:

# fill the screen with a colour

# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:

# Key-presses
if event.type == pygame.KEYDOWN:

# q for quit
if event.key == pygame.K_q:
done = True

# c to change colour
if event.key == pygame.K_c:
blob_col = change_blob(blob_col)

# play sounds if you press 1
if event.key == pygame.K_1:
if sound_num == 5:
sound_num = 0
sound_num += 1

# arrow keys for movement
if event.key == pygame.K_RIGHT:
x_speed = 1
if event.key == pygame.K_LEFT:
x_speed = -1
if event.key == pygame.K_UP:
y_speed = -1
if event.key == pygame.K_DOWN:
y_speed = 1

# make speed 0 when keys released
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = 0
if event.key == pygame.K_UP:
y_speed = 0
if event.key == pygame.K_DOWN:
y_speed = 0

# move the blob
blob_rect.centerx += x_speed
blob_rect.centery += y_speed

# prevent blob moving off screen
if <= = + 10
y_speed = 1
blob_col = change_blob(blob_col)

if blob_rect.bottom >= screen_rect.bottom:
blob_rect.bottom = screen_rect.bottom – 10
y_speed = -1
blob_col = change_blob(blob_col)

if blob_rect.left <= screen_rect.left:
blob_rect.left = screen_rect.left + 10
x_speed = 1
blob_col = change_blob(blob_col)

if blob_rect.right >= screen_rect.right:
blob_rect.right = screen_rect.right – 10
x_speed = -1
blob_col = change_blob(blob_col)

# blit the blob to the screen
screen.blit(blob, blob_rect)

# set the loop to 100 cycles per second

#  update the display

# close pygame

If any of this seems unclear, please leave me a comment!