pls help newbie?

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Tue May 20 19:08:22 EDT 2003


J.P.Wagner wrote:
 > Hi!
 >
 > I wrote some code for a "monkey puzzle"
 > I know that it's totally the wrong way of goin about it, but the idea is
 > there.

Why is this wrong? It works fine!
The only problem is that it's quite "static" code,
you have to do a lot of work to add a new quiz question
or to change the behavior of your program.

 > Can any1 pls help pointing me in the right direction of re-writing this in
 > the "right" way

I don't know what you think (or want) is the "right way",
and how much a "newbie" you are, but but my take at your
quiz program would be something like this:

You're repeatedly asking a question to the user.
So what we need is some sort of loop, that picks the next
question and asks it, untill all questions have been asked:

for question in questions:
	question.ask()

How do we specify the questions? Let's just make a list of all
data that belong to a question: the question text, the possible
answers, and the right answer (a letter from a to z).

questions = [
	Question( "CHET ATKINS", ("drums", "guitar", "piano" ), 'b' ),
	Question( "DORIS BRASCH", ("Francios van Heyningen", "Jurie Ferreira", "Bob Borowski"), 'c' )
     ]


The last thing we need is the Question itself,
that knows how to ask the user and that can
check if the user's answer is correct.


The full program looks like this:

-----------------------------------
import string

class Question:
	def __init__(self, question, answerList, rightAnswer):
		self.question=question
		self.answers=answerList
		self.correct=rightAnswer
	def ask(self):
		print self.question
		letters = list(string.lowercase)
		for answer in self.answers:
			print letters.pop(0)+". "+answer
		if raw_input("What do you think? ")==self.correct:
			print "GOT IT"
		else:
			print "Sorry, the correct answer was",self.correct
			

questions = [
	Question( "CHET ATKINS", ("drums", "guitar", "piano" ), 'b' ),
	Question( "DORIS BRASCH", ("Francios van Heyningen", "Jurie Ferreira", "Bob Borowski"), 'c' )
     ]

for question in questions:
	print
	question.ask()
-----------------------------------

Now, it's very easy to add more questions (just add one to the list),
or to change the way the question is asked and processed (just
change the "ask" method implementation).
Notice that you can vary the number of possible answers too,
but it should be less or equal to 26, because that is the number
of letters in the alphabet (string.lowercase) :-)

-- Irmen de Jong





More information about the Python-list mailing list