Skip to content

Instantly share code, notes, and snippets.

@greenstick
Last active November 7, 2018 05:22
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 greenstick/9a5f774842ebf0382801 to your computer and use it in GitHub Desktop.
Save greenstick/9a5f774842ebf0382801 to your computer and use it in GitHub Desktop.
Python: Get user input from command line
# Prompt user input from command line
def getUserInput (valid, prompt, hint = "", failed = "Error: Invalid input"):
"""
Prompts user for and validates input using regular expression
@params:
valid - Required : regex to validate against (Rgx)
prompt - Required : verbose user prompt (Str)
hint - Optional : input hint (Str)
failed - Optional : failed input (Str)
Returns: dicts (List)
"""
response = input(prompt).strip()
if re.match(valid, response):
return response
print(failed)
return getUserInput(valid, prompt, hint, failed)
#
# Sample Usage
#
likesBananas = False
response = getUserInput(
valid = r"([yYnN]{1}|exit)",
prompt = "Prompt: Do you like bananas?",
hint = "\tHint: enter 'y', 'n', or 'exit' to exit\n\tSelection: ",
failed = "\tError: Invalid input"
)
if response == "exit":
exit()
elif response.lower() == "y" or response.lower() == "yes":
likesBananas = True
else:
pass
if likesBananas is True:
print("Get 'em some banoffee pie!")
if likesBananas is False:
print("Get 'em some plantains.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment