Archive for December, 2015

Simple quiz using a dictionary.

12/12/2015

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 python.org.

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.

dict

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.

"""quiz.py - 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()
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("Correct.")
else:
print("Sorry, correct answer is \"{}\".".format(a))
return score

if __name__ == "__main__":
main()

Print a Christmas Tree

12/12/2015

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.

tree_screenshot

But the coloured “baubles” should flash!

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

Here’s the program:

""" christmas.py 
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 datamungeblog.com.
"""

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
    print(makeTree(SIZE))

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.
            else:
                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__":
    main()