How can my loop branch back to looking for input if there is no work to do?
I’m making a script that essentially asks for 3 or 4 raw_input lines, and then does some work based on those, and loops infinitely. However, the raw_input lines are choices (I’m looking for them to type one of a few statements). Instead of a mess of booleans and while loops to make sure it’s an acceptable statement, I thought it might be easier and cleaner to simply do something like this:
if theInput != 'Acceptable Statement' and theInput != 'Another acceptable statement':
restartLoop()
if theSecondInput != 'Acceptable Statement' and theInput != 'Another acceptable statement':
restartLoop()
And so on, for every input I need. It would abort the current cycle and restart with another, as if it had finished. Since nothing actually happens until all the data is collected and approved, this shouldn’t cause any problems. I realize this is an alternative:
if theInput == 'Acceptable Statement' or theInput == 'Another acceptable statement':
if theSecondInput == 'Acceptable Statement' or theInput == 'Another acceptable statement':
doThings()
else:
doNothing()
else:
doNothing()
However, I’d like it to end the loop after the input the user gets wrong, instead of asking them 5 questions and eventually telling them they got #2 wrong.
EDIT: Just to be a bit clearer, I still want to infinitely loop (nothing but leaving the shell will leave the loop), I just want to restart the loop without completing. IE, when making many of a product, you are in a loop with a few steps. But, if you perform a step incorrectly, you throw out the faulty product and start over without finishing.
Nested
ifs will work just fine, and you can make them neater, too:But
continuewill do what you need. I just find the above nicer-looking 🙂