I am writing software in Python that needs to do the following:
- Assign values to variables by getting input from the user
- Choose the next question to ask the user based on their previous answer
- Take action based on the variables once all questions have been asked
I saw an example on here which set questions in a Python dictionary, and that included what question to jump to based on the answer entered. This was very neat and easy to follow, so I started implementing that. I was then going to follow this by comparing the variables to a second dictionary which would then determine what action to take - a decision matrix I believe this is called.
I came to a grinding halt, however, on a question that asks for the date. I have no idea how to check the date is in the right format, and how to get Python to check a valid date has been entered and, if it has, to move to a specific next question. Turns out there is more than one occurrence of this problem.
The code follows below. You can easily see in questions relating to candate and frequency1 and frequency2 where I have come a cropper.
The question, I guess, is whether I can do this using a dictionary to define questions and flow, or whether I will have to suck it up and create a load of IF statements. The only reason I started with dictionaries is to make it easy to implement, maintain and expand. Once I have nailed this, I need to implement much bigger question sets, so would like the question flow to be as elegant and simple as possible.
Apologies for obfuscating the questions.
If you answer, I would just point out this is the first thing I have tried to write in Python beyond asking for someone's name and printing it so simpler is better for me! Thanks!
#Stopquestions is a dictionary containing all the questions that could be asked of the user. It also controls the flow of the questions.
stopquestions = {
'stopconfirm':
{
'prompt':'Do you want to take this action? Y/N ',
'Y':'prev',
'N':'genericerror'
},
'prev':
{
'prompt':'Previously done? Y/N ',
'Y':'bamerch',
'N':'frequency1'
},
'bamerch':
{
'prompt':'Was that with B or M? B/M ',
'B':'candate',
'M':'candate'
},
'candate':
{
'prompt':'What was the date? DD/MM/YYYY ',
'DD/MM/YYYY':'length',
'Anything but the above':'genericerror'
},
'length':
{
'prompt':'Yes or no with reference to length? Y/N ',
'Y':'frequency2',
'N':'frequency2'
},
'frequency1':
{
'prompt':'Choose freq? W/F/M/Q/A ',
'W/F/M/Q/A':'dis',
'Anything but the above':'genericerror'
},
'frequency2':
{
'prompt':'Choose freq? W/F/M/Q/A ',
'W/F/M/Q/A':'end',
'Anything but the above':'genericerror'
},
'dis':
{
'prompt':'Disagreement with recent? Y/N ',
'Y':'end',
'N':'end'
},
'genericerror':
{
'text':'This is a basic example of how we can catch errors.',
'action':'end'
}
}
Aucun commentaire:
Enregistrer un commentaire