Skip to content

Instantly share code, notes, and snippets.

@creisor
Last active October 26, 2023 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save creisor/76ce13e76c261de2c431bfa020737003 to your computer and use it in GitHub Desktop.
Save creisor/76ce13e76c261de2c431bfa020737003 to your computer and use it in GitHub Desktop.
A somewhat flexible (could be better) user question response
#!/usr/bin/env python3
def ask(question, response_dict):
choices = '/'.join(response_dict.keys())
response = input(f'{question} ({choices}): ').lower().strip()
try:
default = response_dict[[k for k in response_dict.keys() if k.isupper()][0]]
except IndexError:
default = None
try:
if default is not None and not response:
return default
return response_dict[response]
except KeyError:
try:
return response_dict[response.upper()]
except KeyError:
pass
print(f'Please choose from: {choices}')
return ask(question, response_dict)
print(ask('Send email?', {'Y': True, 'n': False}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment