[Tutor] help understanding part of the tutorial...

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu Jan 9 17:23:19 2003


On Thu, 9 Jan 2003, Guess Who? Me wrote:

> # This will run through all the questions
> def run_test(questions):
>     if len(questions) == 0:
>         print "No questions were given."
>         return
>     index = 0
>     right = 0
>     while index < len(questions):
>         if check_question(questions[index]):
>             right = right + 1
>         index = index + 1
>     print "You got ",right*100/len(questions),"% right out
> of",len(questions)


Hi Travis

Hmmm... this code can be improved.  There are a few things we can do:

    1.  Use a for loop instead of a while loop.  As far as I can tell,
        there's no need for a separate "index" variable if we use a 'for'
        loop here.  Since we're "iterating" or going through a list of
        questions, it's much more natural to use a "for" loop.

    2.  Yank our the question asking section into a separate function:
        this might help us better understand the flow of the program if
        the body of each function is tiny.

    3.  Rename "check_question()" to something more obvious like
        "is_question_answered_correctly()".  check_question() does not
        give much clue as to what will be returned if a question is
        answered correctly or not: what are we "checking" for?

        If we rename the function to "is_question_answered_correctly()",
        that makes it more clear that we'll get a true value if the
        user is hitting the right buttons.  *grin*


Programs are not chisled into stone: they can be revised, just like essays
or creative writing.  We shouldn't be afraid to break up the code into
pieces.  We may find that doing a "refactoring" can often help to make the
code less inscrutable.  *grin*


Here's one way we can revise that run_test() function:

###
#             (assume that check_question() has been renamed to
#              is_question_answered_correctly())

def run_test(questions):
    """Asks all questions of a test, and tallies up a percentage of
       correct answers."""
    if len(questions) == 0:
        print "No questions were given."
        return
    right = count_right_answers(questions)
    print "You got ", right*100/len(questions),
    print "% right out of",len(questions)



def count_right_answers(questions):
    """Given a list of questions, asks each question in turn, and returns
       the number of correctly answered questions."""
    number_correct = 0
    for question in questions:
        if is_question_answered_correctly(question):
            number_correct = number_correct + 1
    return number_correct
###


Is this easier to understand?