[Courses] [python] Lesson 6: Functions and dictionaries

lenore borisova orangegirl at gmail.com
Mon Jul 25 05:22:56 UTC 2011


I just wanted to submit a revision to mine - this revises problem 3 in
Homework 6.

I had one issue, where my dictionary contained 9 elements, but I could only
get it to go through 8 of them before there was an IndexError so that's why
I did the len(elements)==1 because I couldn't think of a way around that.
The problem came in when I was trying to delete an element from the
dictionary if the question had already been asked so that it wouldn't mess
up the correct/incorrect count at the end. After a question was asked, it
would loop and then ask another random question from the dictionary. I did
want it to go through all items in the dictionary. I had one-word answers so
for matching all I needed to do was make sure the case was consistent.

So, this revision now adds a condition to test if there are no elements (or
an empty dictionary) - if it is empty, it just breaks the loop and ends the
program, displaying the final count. If it's not empty, it continues to loop
and randomly get a question/answer from the dictionary.

Here is the revised code - and this does work as intended:

import random, sys

elements = {
        "He"    :       "helium",
        "N"     :       "nitrogen",
        "Se"    :       "selenium",
        "Bi"    :       "bismuth",
        "Na"    :       "sodium",
        "Rb"    :       "rubidium",
        "Sn"    :       "tin",
        "Mg"    :       "magnesium",
        "Os"    :       "osmium",
        }


def chem(elements):
        symbol = random.choice(elements.keys())
        answer = elements[symbol]
        return (symbol, answer)

def ui():
        print "*" * 60

def counts():
        print "Time is up! You answered ",
        print tally,
        print "correctly, out of ",
        print total

(symbol, answer) = chem(elements)

ui()
print "PERIODIC TABLE QUIZ"
print "Type the element name and press ENTER (q to quit)"
ui()

tally = 0
total = 0

while True:
        print "Element symbol: " + symbol
        maybe = raw_input("Element name: ")
        maybe = maybe.strip()
        maybe = maybe.lower()
        if maybe == "q":
                ui()
                counts()
                ui()
                break
        else:
            if maybe == answer:
                    print "correct :)\n"
                    tally += 1
            else:
                    print "incorrect :(\n"

            del elements[symbol]

            total += 1

            if len(elements) == 0:
                    ui()
                    counts()
                    ui()
                    break

            (symbol, answer) = chem(elements)


More information about the Courses mailing list