Wednesday, April 4, 2012

I Feel Like a Pro

It took me forever to figure out, but I finally worked out the question-answer confirmation python script that's been driving me crazy for days. Anyone who uses Python can totally borrow this. It's designed to check multiple answers. If you've got a suggestion to make it better, lemme know!

#VALIDATEQA##########################################################
# validateQA() does the following:                                  #
#    asks the question                                              #
#    compares answer to valid options                               #
#    returns list of answers as a string                            #
#####################################################################

def validateQA(question, valid):
    counter = 0
    while counter == 0:
        validAnswerList = []
        givenAnswerList = raw_input(question).split(' ')
        for answer in givenAnswerList:
            if answer in valid.keys():
                validAnswerList.append(valid[answer])
                if len(validAnswerList) == len(givenAnswerList):
                    counter = 1
            else:
                sys.stdout.write("\nAnswer the question, bro!")
    result = ' '.join(validAnswerList)
    return result

Example...
    renameQ = "Would you like to rename this? (y/n): "
    renameA = {"yes":"yes",   "y":"yes",    "ye":"yes",
               "no":"no",     "n":"no"}
    rename = validateQA(renameQ, renameA)
 
    whichQ = "Which characters would you like to rename? (separate with spaces): "
    whichA = {"john":"johndoe",   "doe":"johndoe",    "john doe":"johndoe",
               "jill":"jillian",   "jillian":"jillian"}
    which = validateQA(whichQ, whichA)

Like magic!

No comments:

Post a Comment