SHARE
TWEET

get_input

DeaD_EyE Feb 8th, 2019 (edited) 99 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. def get_input(question, *,
  2.     input_type=str,
  3.     choices_keys=None, choices_values=None,
  4.     value_error_msg=None, choices_error_msg=None,
  5.     encoding='utf8'):
  6.     """
  7.    To do...
  8.    """
  9.     while True:
  10.         text = input(question + ': ')
  11.         if choices_keys:
  12.             text = text.strip().lower()
  13.         if input_type is str and choices_keys and not text in choices_keys:
  14.             if choices_error_msg:
  15.                 print(choices_error_msg, file=sys.stdout)
  16.             continue
  17.         try:
  18.             if input_type is bytes:
  19.                 value = input_type(text, encoding=encoding)
  20.             else:
  21.                 value = input_type(text)
  22.         except ValueError:
  23.             if value_error_msg:
  24.                 print(value_error_msg, file=sys.stdout)
  25.         else:
  26.             break
  27.     if choices_keys:
  28.         index = choices_keys.index(value)
  29.         if choices_values:
  30.             return choices_values[index]
  31.         else:
  32.             return index
  33.     else:
  34.         return value
  35.  
  36.  
  37. square_meters = get_input('How big is your room in m²?', input_type=float)
  38.  
  39. apples = get_input('How many Apples have you eaten last year?', input_type=int)
  40.  
  41. choices = ('yes', 'no', 'maybe') # index of no == 0, index of yes == 1
  42. choices_retvals = [True, False, ...]
  43. execute = get_input(
  44.     'Execute the program? [yes/no/maybe]',
  45.     choices_keys=choices,
  46.     choices_values=choices_retvals)
  47. # try maybe
  48.  
  49. choices2 = ['single', 'dual']
  50. choices2_index = get_input('Single or dual?', choices_keys=choices2)
  51.  
  52. answer1 = get_input('The answer will be converted to bytes with utf8 encoding', input_type=bytes, encoding='utf8')
  53. answer2 = get_input('The answer will be converted to bytes with latin1 encoding', input_type=bytes, encoding='latin1')
  54.  
  55. print()
  56. print('square_meters:', square_meters, type(square_meters))
  57. print('apples:', apples, type(apples))
  58. print('execute:', execute, type(execute))
  59. print('answer1:', answer1, type(answer1))
  60. print('answer2:', answer2, type(answer2))
  61. print('choices2:', choices2_index, type(choices2_index))
  62. print('choices2 content:', choices2[choices2_index])
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top