Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def get_input(question, *,
- input_type=str,
- choices_keys=None, choices_values=None,
- value_error_msg=None, choices_error_msg=None,
- encoding='utf8'):
- """
- To do...
- """
- while True:
- text = input(question + ': ')
- if choices_keys:
- text = text.strip().lower()
- if input_type is str and choices_keys and not text in choices_keys:
- if choices_error_msg:
- print(choices_error_msg, file=sys.stdout)
- continue
- try:
- if input_type is bytes:
- value = input_type(text, encoding=encoding)
- else:
- value = input_type(text)
- except ValueError:
- if value_error_msg:
- print(value_error_msg, file=sys.stdout)
- else:
- break
- if choices_keys:
- index = choices_keys.index(value)
- if choices_values:
- return choices_values[index]
- else:
- return index
- else:
- return value
- square_meters = get_input('How big is your room in m²?', input_type=float)
- apples = get_input('How many Apples have you eaten last year?', input_type=int)
- choices = ('yes', 'no', 'maybe') # index of no == 0, index of yes == 1
- choices_retvals = [True, False, ...]
- execute = get_input(
- 'Execute the program? [yes/no/maybe]',
- choices_keys=choices,
- choices_values=choices_retvals)
- # try maybe
- choices2 = ['single', 'dual']
- choices2_index = get_input('Single or dual?', choices_keys=choices2)
- answer1 = get_input('The answer will be converted to bytes with utf8 encoding', input_type=bytes, encoding='utf8')
- answer2 = get_input('The answer will be converted to bytes with latin1 encoding', input_type=bytes, encoding='latin1')
- print()
- print('square_meters:', square_meters, type(square_meters))
- print('apples:', apples, type(apples))
- print('execute:', execute, type(execute))
- print('answer1:', answer1, type(answer1))
- print('answer2:', answer2, type(answer2))
- print('choices2:', choices2_index, type(choices2_index))
- print('choices2 content:', choices2[choices2_index])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement