Handling yes/no questions from the User

dwelch donald.welch at hp.com
Tue Mar 21 20:11:19 CET 2006


claes_lillieskold at hotmail.com wrote:
> I'm writing a scipt that need to interact with the user.
> Lets say I have the:
> 
> "Do you want to continue [Y|n]"
> 
> Where just pressing return means Yes (since its uppercase).
> 
> Its easy to write a function for this, but perhaps something like this
> already exists. Could someone point me to a class that handles this
> kind of user interaction?
> 
> BR / Claes
> 

I think a class would be overkill. I could see making this into a 
reusable function perhaps.

I just use some code like this (with the '*' indicating the default):

ok = False
while True:
     user_input = raw_input("\nUse this file (y=yes*, n=no, q=quit) 
?").strip().lower()

     if not user_input or user_input == 'y':
         ok = True
         break

     elif user_input == 'q':
         print "Exiting."
         sys.exit(0)

     elif user_input == 'n':
         break

     else:
         print "Please enter 'y', 'n', or 'q'"


-Don



More information about the Python-list mailing list