Sunday, 8 March 2009

Python times tables

My daughter didn't do well at her eight times table at school the other day and wanted me to test her. Instead we both sat in front of her Macbook and bashed out a simple times table tester using python and she got to learn a little bit of vim on the way. She used it for about an hour afterwards and it 'did the trick' for her, which was very satisfying indeed. I seem to remember doing something like this with my Dad :)

At first she was aghast when she realised it would not look pretty, but once we had finished it she loved it! Of course this means that it really would benefit from being written in Flash, but is there an Open Soure flash editor anywhere? Should I consider using silverlight since the linux version is open source? I'll have to look into this.

I've included the times table program below for you if you want it. Enjoy! (Note that it crashes on bad user input, which is not a bad thing as she can just about understand it as it is.)

import random
import sys

# Initialise these variables
is_random = 0
t = 0

print "Times Table Test"
print "What times table do you want to practice"
print "Type 1 - 12, or type 'O' for all"
print ">",
a = sys.stdin.readline()
if a.strip()=="O":
    is_random = 1

print "Okay. Let's go..."

num_right = 0

# Do the stuff with a gap at the start 10 times
for i in range(1,11):

    if is_random == 1:
        t = random.randint(2,12)

    # Multiplication sums to start

    a = random.randint(1, 12)

    print " ", a, "x", t, "= ",

    b = sys.stdin.readline()

    if (a*t)==int(b):
        print "You got it right dude!"
        num_right = num_right + 1
        print "Nope. It's", (a*t)

    # Dividing sums next

    if is_random == 1:
        t = random.randint(2,12)

    a = random.randint(1, 12)

    print " ", (a*t), "/", t, "= ",

    b = sys.stdin.readline()

    if a == int(b):
        print "You got it right dude!"
        num_right = num_right + 1
        print "Nope. It's", a

    # When it gets here it will go back to the start of this block

print "You got", num_right, "out of 20"

if num_right>7:
    print "Whoop whoop. Well done!"

No comments:

Post a Comment