[Courses] [python] Object-oriented programming

Leslie leslie.brothers at verizon.net
Mon Aug 1 21:11:55 UTC 2011


> 
> ========================= Homework =============================
> 
> 1. Write a better loop for that flashcard program so that it exits
> if the user types 'q', and prints out the number right or wrong.
> Hint: you'll probably have to change quiz_user so it returns something
> other than just True or False.

For this exercise, I followed Lenore's previous example of removing each
question as it was shown.


import random

class Flashcard:
	def __init__(self,q,a):
		self.question = q
		self.answer = a

	def print_question(self):
		print self.question

	line = "======================================="

	def quiz_user(self):
		print self.line
		self.print_question()
		print self.line
		ans = raw_input("Type answer or enter 'q' to quit\n")
		if ans.strip().lower() == self.answer.strip().lower():
			print "Good job!"
			return (1, 1)
		elif ans == 'q':
			print "OK, we're done now."
			return (0, 0)
		else:
			print "Sorry, the answer was:", self.answer
			return (0,1)

cards = [
	Flashcard("What is a baby swan called?","cygnet"),
	Flashcard("What is a group of larks called?", "exaltation"),
	Flashcard("How may years does it take Neptune to orbit the sun?",
"165"),
	]

no_correct = 0
total = 0

while cards:
	x = random.choice(cards)
	(y, z) = x.quiz_user()
	if y == 0 and z == 0:
		print "Correct answers: ",no_correct,"  Incorrect answers: ",(total -
no_correct)
		break
	no_correct = y + no_correct
	total = z + total
	print "Correct answers: ",no_correct,"  Incorrect answers: ",(total -
no_correct)
	cards.remove(x)


For the following exercise, I have been struggling a lot. Not having my
printer (to print up versions as I go) is probably making it harder.
But even so, I feel like I am stumped.
I will resume my efforts on the rest of the exercises when I get my new
printer (tomorrow). But since I don't know if I am going to succeed even
then, I will just go ahead and turn in the homework with exercise 1 now.
I hope to have the 'aha' experience when I see other submissions.

-Leslie




> 2. Write a Quiz class that creates flashcards and runs the loop to
> quiz the user.
> 
> 3. (optional) Rewrite your random sentence generation program from
> lesson 5 so it's object oriented. Hint: you could make your list of
> nouns, verbs etc. could be class variables, like "line" in my example
> above.
> 
> 4. (optional) Come up with a better homework assignment for object-
> oriented programming in Python, then solve it. :-)
> _______________________________________________
> Courses mailing list
> Courses at linuxchix.org
> http://mailman.linuxchix.org/mailman/listinfo/courses




More information about the Courses mailing list