TDT4109/common/inputChecking/typeCheck.py

27 lines
681 B
Python
Raw Normal View History

2020-09-15 11:49:55 +02:00
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)
2020-09-15 11:49:55 +02:00
return type(inputValue)
except AssertionError:
print(error)
def validateInput(input, type):
try:
_ = type(input)
return True
except:
return False