[Edu-sig] a non-rhetorical question

kirby urner kirby.urner at gmail.com
Sat Jul 7 09:58:56 CEST 2007


> Here's the most elegant solution I could come up with:
>
> teachers = {'Mr. Judkis':'Excellent Choice',
>             'Mrs. McGrath':'Also a fine choice.'}
> name = raw_input()
> while name not in teachers.keys():
>     print 'Wrong, sorry.'
>     name = raw_input()
> print teachers[name]
>
> --Tom

Here's another solution incorporating Laura's suggestion
that we introduce exception handling earlier rather than
later.  It also emphasizes the imprisoning nature of the
while loop, plus reminds students about the continue
statement:

def pickone(rightanswer):

    inprison = True

    while inprison:

        # ask
        answer = raw_input("Who's the fairest of them all?: ")

        try:
            assert answer.upper() == rightanswer.upper()
        except AssertionError:
            # no good!
            continue  # loop again

        inprison = False

    print "You got it right!"

>>> reload(sillystory)
<module 'sillystory' from '/home/kirby/sillystory.py'>

>>> sillystory.pickone("Evil Queen")
Who's the fairest of them all?: Snow White
Who's the fairest of them all?: President Bush
Who's the fairest of them all?: Obama?
Who's the fairest of them all?: Evil Queen
You got it right!

Good thing to toss in that upper() stuff so a user
doesn't get penalized for capitalizing incorrectly.

As far as testing goes, I think the realistic thing is
to let students write and debug.  Having to write
out code longhand in pencil, with no ability to
check the code is very *not* a simulation of real
programming conditions, where we rely on the
interpreter to close the feedback loop.  This is
akin to Laura's suggestion of focusing on unit
testing, except we're just letting the interpreter
play that role for these simple constructions.

So a testing environment should give free reign
to the docs, as well as to the interpreter.  Then
cut and paste the finished code to a static text
box, if that's what's required.  Any handwriting
should count as marks off the teacher's grade.

Given the above, other questions for the student
might be:  modify the above code to give the user
a hint after 3 false tries, with the hint passed as
a parameter.  Now modify the code further to
cause it to exit, with a failure message, after
ten false guesses.

Kirby


More information about the Edu-sig mailing list