1

One of the recurring feature of a script I am working on is asking the user to input Yes or No. To make the script as dummy-proof as possible, I want to make sure that any inputs other than 'Y', 'y', 'N', and 'n' are all rejected, and the user will be asked to re-enter a value. I wrote a function called test_yes_or_no to help me with this.

def test_yes_or_no(answer):
    if answer in ('Y', 'y'):
        return True
    elif answer in ('N', 'n'):
        return False
    else:
        return None

Here is an example where I use test_yes_or_no:

def main():
    while True:
        ans = raw_input("Yes or no? (Y/N) ")
        if test_yes_or_no(ans) == True:
            #do something
            break
        elif test_yes_or_no(ans) == False:
            #do something
            break
        else:
            print("Invalid answer. Please try again.")

I have many other similar do-while loops that also ask for new raw_inputs() until a valid input is found. (e.g. Make sure that the user enters one single digit) These do-while loops all look something like

while True:
     if condition():
        break
     elif condition2():
        break
     elif condition3():
        break
     elif condition4():
        break
....

As you can imagine, I ended up with many do-while loops like the example above nested on top of each other, and the code quickly became quite messy. Is there a more elegant way to make sure raw_input() returns valid option without writing while True: loops?

Ken Lin
  • 986
  • 1
  • 8
  • 22

0 Answers0