Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' simple calculations using basic operators and input validation v2'''
- LABELS = {int: "integer", float: "floating point number", str: "string"}
- def get_input(msg = '', type_req = int):
- ''' prompt user for input with msg and return appropriately cast value '''
- if not LABELS.get(type_req):
- raise TypeError("Unknown input type requested by calling code.")
- while True:
- response = input(msg)
- if response:
- try:
- value = type_req(response)
- except ValueError as e:
- pass
- else:
- return value
- print(f'{LABELS[type_req]} input required. Please try again.')
- num_x = get_input("enter an integer for x: ")
- num_y = get_input("enter a float (decimal) for y: ", float)
- print(f"x + y = {num_x + num_y}")
- print(f"x - y = {num_x - num_y}")
- print(f"x * y = {num_x * num_y}")
- try:
- print(f"x / y = {num_x / num_y:.4f}")
- except ZeroDivisionError as e:
- print('x / y not possible with 0 divisor')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement