Last active
July 4, 2021 07:50
-
-
Save FelixLuciano/ab8f51dc6f2cb726418ef139b8dbd20f to your computer and use it in GitHub Desktop.
This file contains 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
def valid_input (validator=str, prompt="", accept=None, reject=[], persist=True, apply=None): | |
while True: | |
try: | |
response = validator(input(prompt)) | |
normalized = apply(response) if apply != None else response | |
except ValueError: | |
if persist != False: | |
print("Invalid input!") | |
else: | |
return None | |
except KeyboardInterrupt: | |
print("\nInput canceled!") | |
return None | |
else: | |
if (accept == None or normalized in accept) and normalized not in reject: | |
return response | |
elif persist != False: | |
print("Invalid input!") | |
else: | |
return None |
This file contains 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
# Returns only if an valid integer was input | |
response = valid_input(int) | |
# Returns only if an valid string was input and in lowercase | |
response = valid_input(str.lower) | |
# Returns only if "yes" or "no" was input; | |
response = valid_input(str, "Test str input: ", ["yes", "no"]) | |
# Returns if exactly "y" or "yes" was input, otherwise it returns None; | |
response = valid_input(str, "Test str input: ", ["y", "yes"], persist=False) | |
# Returns if uppercase "Y" or "YES" was input, otherwise it returns None; | |
response = valid_input(str, "Test str input: ", ["Y", "YES"], apply=str.upper) | |
# Returns if not "foo" or "bar" was input, otherwise it returns None; | |
response = valid_input(str, "Test str input: ", reject=["foo", "bar"]) | |
# Returns only if valid integer that is 1, 3 or 5 was input; | |
response = valid_input(int, "Test int input: ", [1, 3, 5]) | |
# Returns only if an valid integer between 1 and 9 was input; | |
response = valid_input(int, "Test int input: ", range(1, 10)) | |
# Returns only if an valid float was input; | |
response = valid_input(float, "Test float input: ") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, Amazing!