Skip to content

Instantly share code, notes, and snippets.

@marcom04
Created March 2, 2017 14:35
Show Gist options
  • Save marcom04/00232aa5bbcc1719c5ed83fb6377f0d4 to your computer and use it in GitHub Desktop.
Save marcom04/00232aa5bbcc1719c5ed83fb6377f0d4 to your computer and use it in GitHub Desktop.
One more question
def ask(question, answers_type=None, answers=None, menu=None, menu_args=None):
""" Ask a question. (duh!)
Params:
- question: a string representing the question to ask
- answers_type: raw input will be casted to this tipe (if None, answer will be kept as string)
- answers: a list containing the feasible answers (if None, the answer can be any)
- menu: a function that prints a user menu
- menu_args: optional parameters to pass to menu function
Returns:
- The answer to life.
"""
ask_again = True
answer = None
while ask_again:
ask_again = False
try:
if menu is not None:
menu(menu_args)
answer = raw_input(question)
if answers_type is not None:
answer = answers_type(answer)
if answers is not None and answer not in answers:
raise ValueError
except ValueError:
print("Wrong choice.")
ask_again = True
except KeyboardInterrupt:
print("\nGoodbye!")
sys.exit(0)
return answer
def main_menu(x):
print("------------------------")
print("Menu # %d:" % x)
print("1. Choice 1")
print("2. Choice 2")
print("3. Choice 3")
print("Ctrl-C to exit")
print("")
def main():
# Ask question that takes generic answer
ans = aks(question="What's up? ")
# Ask question that takes an integer as an answer
ans = ask(question="Give me a number: ", answers_type=int)
# Ask question that takes an integer in a certain range as an answer
ans = ask(question="How old are you? ", answers_type=int, answers=range(0,100))
# Ask question and show a menu of possible answers
ans = ask(question="Select an option: ",
answers=range(1,4), answers_type=int,
menu=main_menu, menu_args=1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment