TDT4109/common/inputChecking/typeCheck.py

27 lines
681 B
Python

def inputTypeCheck(
prompt,
type,
error="Kunne ikke tolke input. Har du skrevet det inn riktig?"
):
"""
Typechecks an input, and only returns the input when it could be successfully parsed.
Parameters: \\
prompt (str): The prompt asking the user for input \\
type (fun): The function to be used for parsing \\
error? (str): The message to be printed on parsing error
"""
while True:
inputValue = input(prompt)
try:
assert validateInput(inputValue, type)
return type(inputValue)
except AssertionError:
print(error)
def validateInput(input, type):
try:
_ = type(input)
return True
except:
return False