Yes No Prompt for python


/ Published in: Python
Save to your folder(s)

Makes it a little easier to ask the user for a yes/no answer


Copy this code and paste it in your HTML
  1. ## {{{ http://code.activestate.com/recipes/577058/ (r2)
  2. def query_yes_no(question, default="yes"):
  3. """Ask a yes/no question via raw_input() and return their answer.
  4.  
  5. "question" is a string that is presented to the user.
  6. "default" is the presumed answer if the user just hits <Enter>.
  7. It must be "yes" (the default), "no" or None (meaning
  8. an answer is required of the user).
  9.  
  10. The "answer" return value is one of "yes" or "no".
  11. """
  12. valid = {"yes":"yes", "y":"yes", "ye":"yes",
  13. "no":"no", "n":"no"}
  14. if default == None:
  15. prompt = " [y/n] "
  16. elif default == "yes":
  17. prompt = " [Y/n] "
  18. elif default == "no":
  19. prompt = " [y/N] "
  20. else:
  21. raise ValueError("invalid default answer: '%s'" % default)
  22.  
  23. while 1:
  24. sys.stdout.write(question + prompt)
  25. choice = raw_input().lower()
  26. if default is not None and choice == '':
  27. return default
  28. elif choice in valid.keys():
  29. return valid[choice]
  30. else:
  31. sys.stdout.write("Please respond with 'yes' or 'no' "\
  32. "(or 'y' or 'n').\n")
  33. ## end of http://code.activestate.com/recipes/577058/ }}}

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.