Posts Tagged ‘Python’

Simple quiz using a dictionary.


I thought I’d share a really simple program that uses Python’s “dictionary” data type.

If you want to read all about dictionaries, head over to the relevant section on

The basic idea of a dictionary is that it’s a way to store data. But instead of using indexes to identify elements in the list, we can use a wide range of different things as “keys”.

Here’s a really silly example.

a = dict()
# Use strings as key and value.
a["big"] = "huge"
# Use integers and floating point numbers.
a[5] = 8.2
a[3.14] = "pi"
# Use a tuple as the key and a boolean as the value.
a[(1,2)] = True
# Use a function as a value.
def plus1(x):
.. return x+1

Here’s what happens when we use those keys to extract items from the dictionary.


So, as you can see, you can use plenty of different data types as the keys and values in a Python dictionary!

I am going to use a dictionary in a very simple way here. Let’s say we have to write a program that does a simple quiz. We could store questions and answers in a pair of lists, or even in a 2d list. But then we would have to access them using array notation (numbers in square brackets). With a dictionary we can use one string (the question) as the “key” which will link with another string (the “value” – in our case the answer).

Here’s the code.

""" - simple quiz program."""

def main():
"""Set up the quiz."""

# The questions and answers are in this dictionary.
qs = {"What's the capital of England? ":"London",
"What's the third planet in the Solar System? ":"Earth",
"Who wrote \"Great Expectations\"? ": "Charles Dickens",
"Who sang \"Someone Like You\"? ":"Adele",
"Who is the current Doctor Who? ":"Peter Capaldi",
"Who is the sheriff in \"The Walking Dead\"? ": "Rick Grimes",
"Which metal is liquid at room temperature? ": "Mercury",
"Who plays Katniss in \"The Hunger Games\"? ": "Jennifer Lawrence",
"Which element combines with hydrogen to make water? ": "Oxygen",
"What is the highest mountain in the UK? ": "Ben Nevis"}

print("*** Quiz ***\n")
name = input("Please enter your name: ").title()
print("\nWell done {0}, you scored {1} out of {2}.".format(name, quiz(qs), len(qs)))

def quiz(qs):
"""Returns a score. Asks questions from qs dictionary."""
score = 0;
# Use the .items() method to get the key / value pairs.
for q,a in qs.items():
if input(q).lower() == a.lower():
score += 1
print("Sorry, correct answer is \"{}\".".format(a))
return score

if __name__ == "__main__":

Print a Christmas Tree


It’s been a long while since I posted anything here, but I have a festive program to share.

I think the comments should make it pretty self-explanatory.

Please note this will not work in Idle, you need to run it in the terminal. I have not tested it in Windows …

The output should look a bit like this.


But the coloured “baubles” should flash!

If you want to download the code, it’s on my github.

Here’s the program:

Prints a christmas tree on the terminal using coloured and blinking characters.
Uses ansi terminal escape sequences.
The '\033[' part is the escape code. 
We pass '5;' for the colours other than green to make them blink.
The next part is the colour code and the 'm' ends the sequence.
To reset the colour we pass "\033[0m" after each character.
Python 3 version by antiloquax (2015), based on code from

from random import choice
from random import random

def main():
    """Make the tree and print it."""
    # If you change this, use an odd number.
    SIZE = 21

def makeTree(size):
    """Creates the tree string."""  
    # Probability that a character will be green.
    prob_gr = 0.6
    # Colour codes.
    colours = [31, 33, 34, 35, 36, 37]
    # Characters to use for decorations. Experiment with these.
    # The chr(169) and chr(174) characters may not work in all terminals
    # (extended ASCII, c and r in a circle).
    decs = ['@', '&', '*', chr(169), chr(174)]

    # Format string for printing blinking characters.
    blink_col = "\033[5;{0}m{1}\033[0m"
    # String to print a green octothorpe ('#').
    leaf = "\033[32m#\033[0m"

    # Width of the tree, will grow by 2 each time.
    width = 1
    # Initialise the tree string, with a star at the top.
    tree = "\n{}*\n".format(' ' * (size))

    """ Main Loop starts now."""
    """ We can't use the normal "format" centering approach:
        ("{:^nn}".format(string) where "nn" is the width of the line), 
        with these ansi codes. This is because Python sees the strings as being
        more than one character long (15 & 10 for baubles and leaves)."""

    # Loop from (size - 1) down to 0, using the counter as the padding size.
    for pad in range(size - 1, -1, -1):
        # Increase the width of the tree by 2.
        width += 2
        # Put the characters for the line in "temp".
        temp = ""
        for j in range(width):
            # Make some leaves.
            if random() < prob_gr:
                temp += leaf
            # And also some baubles.
                temp += blink_col.format(choice(colours), choice(decs))

        # Add that string to the line, with padding.
        tree += "{0}{1}\n".format(' ' * pad, temp)

    # Add a "trunk" of 2 lines and return.
    return tree + "{0}{1}\n".format(' ' * (size - 1), "000") * 2

if __name__ == "__main__":

RSA Algorithm


I have put together some short articles with sample code, all based on mathematical algorithms in Python.

Series One

1: A. M. Legendre, exponentiation by successive squaring.
2: Heron of Alexandria, square roots
3: Peano arithmetic
4: Zeller’s congruence
5: Factorial
6: Fibonacci numbers
7: Euclid’s GCD & prime factors
8: Eratosthenes’ Sieve and the Miller-Rabin algorithm
9: Pascal’s triangle
10: Tau using Gregory and Euler’s equations

Series Two

1. Newton’s method for nth roots.
2. Primes revisited
a) faster Miller-Rabin
b) Lucas-Lehmer number
3. A Little Number Theory
a) Ramanujan’s Highly Composite Numbers
b) Ramanujan and Hardy – roundness
c) Pythagoras – perfect numbers
d) Pythagoras – friendly numbers
4. Pi
a) Euler’s method for calculating Pi
b) Cesaro / Monte Carlo method
5. The RSA algorithm

The .zip file is here.

As a little taster, here is the code of my RSA algorithm program. You can copy and paste it and have a play and download the .zip file to read my notes in the pdf file.

# - demo of the RSA algorithm

def main():
    n = e = d = 0
    while 1:
    1. Set Public Key
    2. Encode
    3. Decode
    0. Quit
    Your choice? """, end = "")
        choice = int(input())
        if not choice:
        if choice == 1:
            n, e, d = set_keys()
        if choice == 2:
            if not n:
                n = int(input("Public Key: "))
                e = int(input("e: "))
            encode(n, e)
        if choice == 3:
            if not d:
                n, e, d = set_keys()
            decode(d, n)

def set_keys():
    """This fuction asks for 2 primes.
    It sets a public key and an encoding number, 'e'."""
    p = int(input("p: "))
    q = int(input("q: "))
    n = p * q
    m = (p - 1) * (q - 1)
    e = get_e(m)
    print("N = ", n, "\ne = ", e)
    d = get_d(e, m)
    while d < 0:
         d += m
     return [n, e, d]

     def encode(n, e):
     """This function asks for a number and encodes it using 'n' and 'e'."""
     while 1:
         c = int(input("Number to encode: "))
         if not c:
         print(pow(c, e, n))

 def decode(d, n):
     """This function asks for a number and decodes it using 'd' and 'n'."""
     while 1:
         c = int(input("Number to decode: "))
         if not c:
             print(pow(c, d, n))
  def even(x):
     """True if x is even."""
     return x % 2 == 0

  def get_e(m):
     """Finds an e coprime with m."""
     e = 2
     while gcd(e, m) != 1:
         e += 1
     return e

 def gcd(a,b):
     """Euclid's Algorithm: Takes two integers and returns gcd."""
     while b > 0:
        a, b = b, a % b
    return a

def get_d(e, m):
    """Takes encoding number, 'e' and the value for 'm' (p-1) * (q-1).
    Returns a decoding number."""
    x = lasty = 0
    lastx = y = 1
    while m != 0:
        q = e // m
        e, m = m, e % m
        x, lastx = lastx - q*x, x
        y, lasty = lasty - q*y, y
    return lastx

if __name__ == "__main__":

You can download a .zip file with the other short articles and programs here.


Download WaryPy.vdi for VirtualBox


A few people have commented saying that they have tried to run RacyPy in VirtualBox and run into problems with PAE.

I’ve made a .vdi based of “WaryPy”. No PAE required.


MD5 sum:



My modifications to Liam Fraser’s PiShooter


I am a big fan of Liam Fraser’s tutorials on YouTube. I wanted to change PiShooter so that there was an explosion when you hit the Pi. I made a few changes to Liam’s code. Becuase I am only just getting to grips with pygame, I didn’t make a class for my explosion – I just found a “quick and dirty” was to achieve my goal.

First,  I loaded up an explosion image into “boom”.

Then I added a bit to the collision detection part.

I stored the location of the shot in x1 and y1. Then, if there was a hit, I killed the Pi sprite and made a new one (so the one we hit disappears and a new one begins again at x=0. I’ve made a variable “count” and then in the main loop I blit the explosion to the screen for 20 frames. On my computer this is enough to make the explosion visible (but my laptop is pretty slow!)


Use pygame to make a gui.


Remember that I said the main loop in our tkinter gui program was like a pygame graphics window? Well in this post I am going to use pygame to make a gui.

Here’s the code.

[Note – I will add to this post later!]

Getting started with GUIs


So far all the programs I’ve done on here have been decidedly old-school and run in the command line. As I’ve mentioned before, I am learning as I go and I haven’t got very far yet with using GUIs, but I thought I’d do a post that uses the tkinter features of Python to make GUIs.

Here’s what our first GUI will look like. You can move it, resize it, minimise it and click the button (although it doesn’t do anything!).

Here’s the code.

The first line imports the tkinter modules we need. The next lines create a window and give it a size and a title. You can play around with changing these aspects, if you like. We are using a “class” within tkinter here. We’re getting into Object Oriented Programming with this little script. The line: “root = Tk()” makes a new object: an instance of the class “Tk”. We can then use some of the “methods” which that class contains. The method “title” sets the title and “geometry” defines the size.

The dot notation shows us that we are using methods. We have used this type of thing before, for instance, to raise a number to a power we said something like:

i = math.pow(2, 3)

Here the dot notation shows that we are using one of the methods defined in the math module. This one is called “pow” and it raises the first number to the power of the second. An even better example would be when we sorted a list:


Here we have created a list (“mylist”) and we use its name followed by “.sort()” to get the list-method “sort” to order our list.

Next we need a “frame” within the window, and a button. The “.grid()” method causes the layout manager to make the items we have created visible.

At the end of the code we start the main loop. This makes the window keep displaying itself on the screen and checking for any action the user might make. You may have seen similar things if you’ve had a go at pygame in which our graphics windows are controlled by a loop which runs continually until we quit the game.

I hope this makes sense! Anyway, the code itself is pretty simple. Look out for more GUI posts!




The version of the Java Development Kit you have installed in RacyPy2 is 1.7.0_02.

Firstly, I’d like to recommend Herbert Schildt’s books. I am using “Java: The Complete Reference”.

You can download the (free) first chapter of his “Java: A Beginner’s Guide” from various places online.

I am not going to write a lot about Java here – it’s better if you read the Schildt chapter. But I will mention that in Java, all programs use the Object Orientated programming model. We will get around to using this approach in Python (it’s very useful and amazingly powerful). But for simple programs, we haven’t really needed to use it.

What this means in practice is that every Java program has at least one “class”. Here’s an example:

The first four lines are a multi-line comment – we use /* to start these and */ to close them.

Next we have the command that declares the main “class”  of the program. It’s essential that this has the same name as the name of the file. It’s traditional to give this class an initial capital letter. Java is case-sensitive. So if i have called my file “”, my class has to be called “Hello” (not “hello”). The curly braces “{” are used to group a block of code – here the contents of this class.

The next line is a single-line comment which we do by starting the line with “//”.

The next line is one you will see in almost all Java programs (I think – I am only a learner!). I’m not entirely sure what each of the commands means yet! But the important thing is that this line include the call to “main()” which all Java programs need. The next curly brace opens a new code-block – this time for what our program will actually do. What this line actually does is to invoke a class called “System” which gives us control of things like output to the screen. Within this class there is a method called “out” which does just that – outputs to the screen. The “println()” bit is just like print() in Python3 – it will print what we put inside the brackets – in this case a string enclosed in quotation marks – and add a newline. The line ends with a semi-colon because all “statements” in Java must end with a semi-colon. The lines that don’t end in semi-colons are not actually “statements” (yes – I found this a bit confusing at first, but you’ll get the hang of it!).

Then we close the curly braces that enclose the “main()” part of our code, and finally close the curly braces that end the description of our class “Hello”.

Anyway, the fun bit comes next! We have to compile our program!

Open a terminal in the directory where you saved “”. Then type:


This compiles your program into Java bytecode. You then issue the command:

java Hello

And your program should run.

Just to make this really clear, I’ve done a few extra commands here. Typing “pwd” displays the directory we are in. Then “ls” lists the files in it. As you can see, there’s just the file “Hello,java”. Once we have run “javac” a new file is created: “Hello.class”. When we type: “java Hello”, Java looks for a class called “Hello” and executes it, printing: “Hello World!”.

Wow, are you having fun yet!


C++ (and other things) in RacyPy2


If you want to compile in RacyPy2, you need to load the devx file.

It is on the cd (it’s called “devx_racy_5.2.2.sfs”).

If you want to compile you’ll need to do a frugal install (this is quite simple and if you need some help, go to the Puppy Linux forum, or leave me a comment).

Then you need to put the devx file in your /mnt/home folder.

Then choose Menu > System > BootManager.

Click on the button at the top that mentions sfs files. Your devx file should appear in the list on the left. Click it and add it to the list on the right. Then reboot the machine and you will be able to compile.

There is one little problem with this – when you load the devx it will break the script that launches the Python2 IDLE when you click on this snake on the desktop.

I will sort this out for the next release. In the meantime all you need to do is download this .pet (choose open with PetGet) and it will fix the problem!

Happy compiling!


“Guess my Number” in Scratch


I like Scratch! I was having a play with it yesterday and made this. I had to use nested if … else commands because there doesn’t seem to be away to do something like “elif”. If you know a better way to do it, please tell me!