Last active
November 7, 2018 05:22
-
-
Save greenstick/9a5f774842ebf0382801 to your computer and use it in GitHub Desktop.
Python: Get user input from command line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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