python - How to make a tree-like survey avoiding excessive usage of if statements? -
i'm trying create questionnaire each answer leads different question (similar decision tree does).
it fairy simple accomplish using if-else statements, expect have more branches , depth "tree".
i'm afraid @ point won't able read code anymore.
is there cleaner, easy read way write this?
here's example of figure out far:
q1 = raw_input("q1 \n\n1)\n\n2)\n\n3)\n") if q1 == "1": q2 = raw_input("q1.1 \n\n1)\n\n2)\n\n") if q2 == "1": q3 = raw_input("q1.1.1 \n\n1)\n\n2)\n\n3)\n\n") if q2 == "2": q3 = raw_input("q1.1.2 \n\n1)\n\n2)\n\n3)\n\n") if q1 == "2": q2 = raw_input("q1.2 \n\n1)\n\n2)\n\n3)\n\n") if q2 == "1": q3 = raw_input("q1.2.1 \n\n1)\n\n2)\n\n") if q2 == "2": q3 = raw_input("q1.2.2 \n\n1)\n\n2)\n\n") if q2 == "3": q3 = raw_input("q1.2.3 \n\n1)\n\n2)\n\n3)\n\n") if q1 == "3": q2 = raw_input("q1.3 \n\n1)\n\n2)\n\n3)\n\n4)\n\n") if q2 == "1": q3 = raw_input("q1.3.1 \n\n1)\n\n2)\n\n") if q2 == "2": q3 = raw_input("q1.3.2 \n\n1)\n\n2)\n\n") if q2 == "3": q3 = raw_input("q1.3.3 \n\n1)\n\n2)\n\n") if q2 == "4": q3 = raw_input("q1.3.4 \n\n1)\n\n2)\n\n")
you're going have specify structure of questionnaire in way, , that's going verbose because has include question text , answer choices. can separate different parts of application logic - in particular, separate question , answer definitions processing of input , printing of output, , might make code bit cleaner.
one way might decent create class represent question , answers. instance of class allow retrieve next question depending on answer given. this:
class question: def __init__(self, question, answers): # question string, answers list of n strings def set_next(self, answer_choice, next_question): # answer_choice index 0 n-1 , # next_question question object should used # next if answer chosen def ask(self): # prints self.question , answers using raw_input() # , returns question object (if any) set # set_next() corresponds user typed
then can turn questions instances of object:
q1 = question('what up?', ['down', 'left', 'right']) q11 = question('something down?', ['a', 'b']) q1.set_next(0, q11) # etc.
and can keep asking questions using simple loop:
question = q1 while question not none: question = question.ask()
there various ways make more elegant, started. note you'd doing here making directed acyclic graph (dag) of question objects. if web search, can read more on dags , other methods of representing , processing them might prefer use.
Comments
Post a Comment