Search code examples
pythonpython-3.xfunctionrecursionlogic

Python Questionnaire Validation with Recursion


I've created a function in Python to review a series of questions in a dictionary and remove records from the dataset depending on the answers to the questionnaire. I've created the questionnaire so the user can only respond yes or no. I have a third branch to handle the case where the user responds with something other than yes or no, but I want the function to repeat the existing question. Currently, it goes back and restarts from the first question. What can I add to fix this functionality?

For reference, here is the function I created:

def questionnaire(df, questions = questions):
    for i in range(0, len(questions)): #len(questions)-1):
        print(list(questions.keys())[i])
        
        ans = str(input())
        if ans.lower() == 'yes':
            if list(questions.values())[i][1] == "Yes":
                df = df[df.Section.isin(list(questions.values())[i][0]) == False]
        elif ans.lower() == 'no':
            if list(questions.values())[i][1] == "No":
                df = df[df.Section.isin(list(questions.values())[i][0]) == False]
        else:
            print("Please type yes or no.")
            questionnaire(df, questions = questions)
        
    return df

Solution

  • This should work for your problem:

    def questionnaire(df, questions=questions):
        for i in range(0, len(questions)):  #len(questions)-1):
            print(list(questions.keys())[i])
            ans = None
            while ans not in ['yes', 'no']:
                print("Please type yes or no.")
                ans = str(input()).lower()
            if ans == 'yes':
                if list(questions.values())[i][1] == "Yes":
                    df = df[df.Section.isin(list(questions.values())[i][0]) ==
                            False]
            else:
                if list(questions.values())[i][1] == "No":
                    df = df[df.Section.isin(list(questions.values())[i][0]) ==
                            False]
        return df
    

    So you can transform it to this code:

    def questionnaire(df, questions=questions):
        for i in range(0, len(questions)):  #len(questions)-1):
            print(list(questions.keys())[i])
            ans = None
            while ans not in ['yes', 'no']:
                print("Please type yes or no.")
                ans = str(input()).lower()
            question = list(questions.values())[i]
            if question[1] == ans.title():
                df = df[df.Section.isin(question[0]) == False]
        return df