Skip to content

Instantly share code, notes, and snippets.

@FelixLuciano
Last active July 4, 2021 07:50
Show Gist options
  • Save FelixLuciano/ab8f51dc6f2cb726418ef139b8dbd20f to your computer and use it in GitHub Desktop.
Save FelixLuciano/ab8f51dc6f2cb726418ef139b8dbd20f to your computer and use it in GitHub Desktop.
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
# 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: ")
@gustavoeso
Copy link

Wow, Amazing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment