[Courses] [python] Lesson 6: Functions and dictionaries
lenore borisova
orangegirl at gmail.com
Sat Jul 23 08:15:06 UTC 2011
Below are my answers for Lesson 6:
[Courses] [python] Lesson 6: Functions and dictionaries
1. Random dictionary-o-rama
import random
carracks = { "Mayflower" : "Christopher Jones",
"Santa Maria" : "Juan de la Cosa",
"Victoria" : "Ferdinand Magellan",
"Sao Gabriel" : "Vasco da Gama"
}
def ships(carracks):
ship = random.choice(carracks.keys())
master = carracks[ship]
return (ship, master)
(ship,master) = ships(carracks)
print "Famous carrack: " + ship + " and its master: " + master
----------------------------------------------------------
2. Flashcards
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
(symbol, answer) = chem(elements)
ui()
print "PERIODIC TABLE FLASHCARDS"
print "Press the ENTER key when you are ready to see the answer (q to quit)"
ui()
while True:
user = raw_input(symbol)
if user == "q" :
ui()
print "\nThanks for playing!"
break
print answer
(symbol, answer) = chem(elements)
----------------------------------------------------------
3. User Input - For the correct/incorrect answer part, mine has both the
immediate feedback of a correct/incorrect answer and also the total in
numeric form of questions that were correct as well as the total number that
the user answers - those display after the user types q to quit. I also
removed an element from the dictionary after it was already asked so that it
would not mess up the number of questions asked (no repeats).
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 len(elements) == 1:
ui()
counts()
ui()
break
else:
if maybe == answer:
print "correct :)\n"
print len(elements)
tally += 1
else:
print "incorrect :(\n"
del elements[symbol]
(symbol, answer) = chem(elements)
total += 1
More information about the Courses
mailing list