Advertisement
Inksaver

kboard class for gettting user input

Oct 4th, 2017 (edited)
392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.35 KB | None | 0 0
  1. '''
  2.    This file is kboard.py: https://pastebin.com/UceAJsaV version 1.1
  3.     Demo available from https://pastebin.com/CkfybTVb
  4.    
  5.    kboard static class returns string, integer, float, boolean and menu choices
  6.     Use:
  7.     import kboard as kb #shortens the class name to kb
  8.    
  9.     user_name = kb.get_string("Type your name", True) # returns user input in Title Case
  10.    
  11.     user_age = kb.get_integer("How old are you", 5, 120) # gets an integer between 5 and 120 from the user
  12.    
  13.     user_height = kb.get_float("How tall are you in metres?", 0.5, 2.5) # gets a float between 0.5 and 2.5 from the user
  14.    
  15.     user_likes_python = kb.get_boolean("Do you like Python? (y/n)") # returns True or False from the user
  16.    
  17.     menu_list = ["Brilliant", "Not bad", "Could do better", "Rubbish"]
  18.     user_choice = kb.menu("What do think of this utility?", menu_list)
  19.     print(f"User thinks this utility is: {menu_list[user_choice]}")
  20.    
  21.     kb.get_string("Press Enter to Quit", False, 0, 20) # Used instead of input("Press Enter to Quit")
  22.     at the end of a file to prevent the console closing (does not apply when run from IDE)
  23.  
  24. '''
  25. def process_input(prompt, min, max, data_type):
  26.     ''' This function is not called directly from other files. Python does not have a 'Private' keyword'''
  27.     valid_input = False
  28.     while valid_input is False:
  29.         print(prompt, end="_")
  30.         user_input = input()    # Could use: user_input = input(f"{prompt}_"), but these 2 lines can be used with other languages
  31.         if len(user_input) == 0:
  32.             print("\nJust pressing the Enter key doesn't work...")
  33.         else:
  34.             if data_type == "bool":    
  35.                 if user_input[0].lower() == "y":
  36.                     user_input = True
  37.                     valid_input = True
  38.                 elif user_input[0].lower() == "n":
  39.                     user_input = False
  40.                     valid_input = True
  41.                 else:
  42.                     print("\nOnly anything starting with y or n is accepted...")
  43.             else:
  44.                 try:
  45.                     if data_type == "int":
  46.                         user_input = int(user_input)
  47.                     elif data_type == "float":
  48.                         user_input = float(user_input)             
  49.                        
  50.                     if user_input >= min and user_input <= max:
  51.                         valid_input = True
  52.                     else:
  53.                         print(f"\nTry a number from {min} to {max}...")
  54.                 except:
  55.                     print(f"\nTry entering a number - {user_input} does not cut it...")
  56.            
  57.     return user_input
  58.            
  59. def get_string(prompt, with_title = False, min = 1, max = 20): # with_title, min and max can be over-ridden by calling code
  60.     ''' Public method: Gets a string from the user, with options for Title Case, length of the string. Set min to 0 to allow empty string return '''
  61.     valid = False
  62.     while not valid:
  63.         user_input = input(prompt + "_").strip()    # change '_' for any preferred character eg '>'
  64.         if len(user_input) == 0 and min > 0:
  65.             print("\nJust pressing the Enter key or spacebar doesn't work...")
  66.         else:      
  67.             if len(user_input) >= min and len(user_input) <= max:
  68.                 if with_title:
  69.                     user_input = to_title(user_input)   # Python has string.title() function. C#, Lua and Java do not, so not used here
  70.                 valid = True
  71.             else:
  72.                 print(f"\nTry entering text between {min} and {max} characters...")
  73.  
  74.     return user_input
  75.    
  76. def get_integer(prompt, min = 0, max = 65536): # min and max can be over-ridden by calling code
  77.     ''' Public Method: gets an integer from the user '''
  78.     return process_input(prompt, min, max, "int")
  79.  
  80. def get_float(prompt, min = 0.0, max = 1000000.0): # min and max can be over-ridden by calling code
  81.     ''' Public Method: gets a float from the user '''
  82.     return process_input(prompt, min, max, "float")
  83.    
  84. def get_boolean(prompt):
  85.     ''' Public Method: gets a boolean (yes/no) type entries from the user '''
  86.     return process_input(prompt, 1, 3, "bool")
  87.  
  88. def to_title(input_text):
  89.     ''' Private Method: makes text into Title Case '''
  90.     temp_list = list(input_text.lower())
  91.     for index in range(len(temp_list)):
  92.         if index == 0:
  93.             temp_list[0] = temp_list[0].upper()
  94.         elif temp_list[index - 1] == " ":
  95.             temp_list[index] = temp_list[index].upper()
  96.  
  97.     return ''.join(temp_list)
  98.  
  99. def menu(title, menu_list):
  100.     ''' displays a menu using the text in 'title', and a list of menu items (string) '''
  101.     print(title)
  102.     for i in range(1, len(menu_list) + 1):    # this range numbers the menu items starting at 1
  103.         print(f"\t{i}) {menu_list[i - 1]}")   # -1 as the iterator starts at 1 instead of 0
  104.        
  105.     return get_integer(f"Type the number of your choice (1 to {len(menu_list)})", 1, len(menu_list)) - 1 # -1 to return correct list index
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement