Advertisement
gruntfutuk

validate

Jul 31st, 2018
374
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. ''' simple calculations using basic operators and input validation v2'''
  2.  
  3. LABELS = {int: "integer", float: "floating point number", str: "string"}
  4.  
  5. def get_input(msg = '', type_req = int):
  6.     ''' prompt user for input with msg and return appropriately cast value '''  
  7.     if not LABELS.get(type_req):
  8.             raise TypeError("Unknown input type requested by calling code.")
  9.     while True:
  10.         response = input(msg)
  11.         if response:
  12.             try:
  13.                 value = type_req(response)
  14.             except ValueError as e:
  15.                 pass
  16.             else:
  17.                 return value
  18.         print(f'{LABELS[type_req]} input required. Please try again.')
  19.  
  20.  
  21. num_x = get_input("enter an integer for x: ")
  22. num_y = get_input("enter a float (decimal) for y: ", float)
  23. print(f"x + y = {num_x + num_y}")
  24. print(f"x - y = {num_x - num_y}")
  25. print(f"x * y = {num_x * num_y}")
  26. try:
  27.     print(f"x / y = {num_x / num_y:.4f}")
  28. except ZeroDivisionError as e:
  29.     print('x / y not possible with 0 divisor')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement