[Tutor] redundant code
Greg Chapman
greg@gregmchapman.info
Sat May 10 00:02:02 2003
>there's a better way to do what I've done. Anyway, I've written this little
>thing to prompt for answers to simple multiplication problems, and I'm
>wondering if anyone would care to comment on it. It bothers me that I have
>to use the exact same line twice, but I can't figure out how to change
>that. Plus it bothers me that the whole thing doesn't fit into one
>function. Anyway, I'd appreciate any comments.
I'm something of a newbie myself, so I can't completely answer your question
(I can't think of how to make it one function cleanly) but this gets rid of
some of the redundant code:
from random import randrange
from sys import exit
from string import lower
def question():
n1 = randrange(1, 10)
n2 = randrange(1, 10)
answer = int(raw_input('How much is %d times %d? ' % (n1, n2)))
if answer != n1 * n2:
return 1
else:
return 0
while 1:
if question():
print "No. Try again."
else:
print "Yes, that is correct."
again = str(raw_input("Would you like another question (type Y or
N)?"))
if lower(again) == "y":
pass
else:
exit()
HTH, and I'm sure someone else will chime in with even better ways of doing
it.
greg