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

Leslie leslie.brothers at verizon.net
Sun Jul 24 20:47:33 UTC 2011


On Fri, 2011-07-22 at 14:37 -0700, Akkana Peck wrote:
> Today's lesson covers defining your own functions, plus
> a fantastically useful data type called a dictionary.
> 
My answers to homework follow, but first:	

I have 2 questions about raw_input. 
	(1)  I would like to be able to put some text plus a variable in the
raw_input string expression, but if I do that, the comma between them
signals two arguments, whereas raw_input only expects one.
	For example,  I have randomly selected a key from my dictionary, and
named it 'species’; now  I want to get the user’s response to this:
“What is [species] nesting site?” and compare it to a value (nesting
sites).  If I say x = raw_input (“What is”, species,”nesting site?”),
raw_input doesn’t like that.  (I suspect there may be no fix but to
print the variable in a separate statement.)
	(2) Let’s suppose my keys are questions.  I randomly choose one and
name it 'question’. I would like to use that for my raw_input expression
(x = raw_input(question)) with a line return at the end, so that the
user enters her response on the next line, not right on the same line as
the question.  I was trying to use \n in various ways at the end of the
raw_input statement but could not make it work.  Can I get a pointer on
this?

	(I read up on raw_input in python ‘help’ and it just says the prompt
string is printed without a trailing newline.)


> ===================== Homework ===========================
> 
> 1. Write a function that takes a dictionary as argument, chooses a random
>    key from that dictionary, and returns the key and its value as a tuple.

import random

birds= {	"yellow-nosed albatross"	:   "Tristan da Cunha",
		"indigo bunting"		:   "Mexico",
		"Scott's oriole"		:   "California",
		"common yellowthroat"		:   "Central America"
	}

def showRandomBird(b):
	species = random.choice(b.keys())
	return (species, b[species]) 
	
our_bird, nesting_site = showRandomBird(birds)
print "Our bird is the",our_bird,"and its nesting site is",nesting_site
+"."


> 
> 2. Use the function you just defined to make a flashcard program.
>    The flashcards can be on any subject you want (or a mix of
>    subjects).  Make a dictionary of questions and answers -- the keys
>    are the questions, the answers are the values. Then use your
>    function to pick a random question/answer pair, print the question
>    and wait for the user to hit return. Then print the answer.
>    (The user can keep track of whether she got it right.)

import random
quiz = {"What is the capital of Somalia?":	  "Mogadishu",
	"Who is the Senate minority leader?":	  "Mitch McConnell",
	"Who played Dorothy in 'The Wizard of Oz'?":"Judy Garland",
	"Who wrote 'War and Peace'?":		  "Leo Tolstoy",
	"Who is the coolest Python teacher ever?":"Akkana Peck",
	"How much chocolate is too much?":	  "No such quantity exists."
	}

def showRandomQuestion(q):
	question = random.choice (q.keys())
	return (question, q[question])
while True:
	question, answer = showRandomQuestion(quiz)
	print "Question: ",question,"\n"
	x = raw_input("Hit Enter to see the answer or 'q' to quit.")
	if x == 'q':
		print "Bye"
		break
	print "\tAnswer: ",answer, "\n"


> 3. Change your flashcard program so that the user has to type the answer,
>    and you compare it against the right answer and keep track of how
>    many were answered right or wrong.
> 

import random
quiz = {"What is the capital of Somalia?":	  "Mogadishu",
	"Who is the Senate minority leader?":	  "Mitch McConnell",
	"Who played Dorothy in 'The Wizard of Oz'?":"Judy Garland",
	"Who wrote 'War and Peace'?":		  "Leo Tolstoy",
	"Who is the coolest Python teacher ever?":"Akkana Peck",
	"How much chocolate is too much?":	  "No such quantity exists."
	}

def showRandomQuestion(q):
	question = random.choice (q.keys())
	return (question, q[question])
n= 0
while True:
	question, answer = showRandomQuestion(quiz)
	print "Enter the answer to the following question, or type 'q' to quit:
\n"
	x = raw_input(question)
	if x == 'q':
		print "You got",n,"right! Bye."
		break
	# the next section does an inflexible test of accuracy of response
	if x == answer:
		print "That's right!"
		n +=1
	else:
		print "Sorry, incorrect."

>    Note: you may find this is kind of a pain, because if you make any
>    typos or add extra spaces or anything you don't get credit for a
>    right answer. If you find this to be a problem, do you have any ideas
>    for ways you could make it more flexible?

My strategy for making the response evaluation more flexible was to make
all comparisons in lower case (since many people don’t bother with upper
case), and to try for a first word match.

I initially tried for a match of any word in the user input with any
word in the actual answer, but the for- and if- loops got beyond me,  as
far as how to break out of them when a match was found.  I’ll have to go
back to that another day.  Here is what I did:

import random
quiz = {"What is the capital of Somalia?":	  "Mogadishu",
	"Who is the Senate minority leader?":	  "Mitch McConnell",
	"Who played Dorothy in 'The Wizard of Oz'?":"Judy Garland",
	"Who wrote 'War and Peace'?":		  "Leo Tolstoy",
	"Who is the coolest Python teacher ever?":"Akkana Peck",
	"How much chocolate is too much?":	  "No such quantity exists"
	}

def showRandomQuestion(q):
	question = random.choice (q.keys())
	return (question, q[question])
n= 0
while True:
	question, answer = showRandomQuestion(quiz)
	print "Enter the answer to the following question, or type 'q' to quit:
\n"
	x = raw_input(question)
	if x == 'q':
		print "You got",n,"right! Bye."
		break
	# the next section performs a flexible test of accuracy of response
	# first change both user input and answer to lower case
	user_lower = x.lower()
	answer_lower = answer.lower()
	#next see whether the first word in user response matches the first
word in answer
	userWords = user_lower.split()
	answerWords = answer_lower.split()
	
	if (userWords[0]) == answerWords[0]:
		print "The first word in your response matches. So it might be
correct."
		n +=1
		if x.lower() == answer.lower():
			print "In fact, your response is an exact match."
	else:
		print "Your response doesn't match."

***************************
I am sending this in before I look at Lenore’s work. I am looking
forward to seeing what she did, and to what others are going to submit.

-Leslie
> _______________________________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses




More information about the Courses mailing list