Create a helper function, input_as
:
from typing import TypeVar, Type
_T = TypeVar('_T')
def input_as(prompt: str, tp: Type[_T], reprompt=True) -> _T:
if '?' not in prompt:
prompt += '? '
elif not prompt.endswith(' '):
prompt += ' '
while True:
ans = input(prompt)
try:
if tp is str:
if ans.lstrip('-').replace('.', '', 1).isnumeric():
raise ValueError('Invalid Numeric') from None
return ans
elif tp in (int, float):
try:
return tp(ans)
except ValueError:
raise ValueError('Invalid String, need a Number') from None
elif tp is not None:
raise NotImplementedError(f"[{tp.__qualname__}] I don't know that type!")
except ValueError as e:
if reprompt:
print(f'{e}, please re-enter.')
else:
raise
Usage:
name = input_as("What's your name", str)
age = input_as("What's your age", int)
print(f'You are {name} and you are {age} years old')
Examples:
What's your name? 123
Invalid Numeric, please re-enter.
What's your name? -1.23
Invalid Numeric, please re-enter.
What's your name?
What's your name? someone
What's your age? idk
Invalid String, need a Number, please re-enter.
What's your age?
(Happy Path)
What's your name? Jimmy
What's your age? 3
You are Jimmy and you are 3 years old