Advertisement
gruntfutuk

console calculator

Jul 20th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. ''' simple console based calculator '''
  2.  
  3. import operator as op
  4.  
  5. OPERATORS = {
  6.             '**': op.pow,
  7.             '^' : op.pow,
  8.             '*' : op.mul,
  9.             '/' : op.truediv,
  10.             '//': op.floordiv,
  11.             '+' : op.add,
  12.             '-' : op.sub,
  13.             '%' : op.mod,
  14.             '<' : op.lt,
  15.             '<=': op.le,
  16.             '==': op.eq,
  17.             '!=': op.ne,
  18.             '>=': op.ge,
  19.             '>' : op.gt,
  20. }
  21.  
  22. def get_num(msg):
  23.     ''' promt for and return numeric input - reject responses that are not integer or float '''
  24.     while True:
  25.         response = input(msg)
  26.         value = None
  27.         if response:
  28.             try:
  29.                 value = float(response)
  30.                 value = int(response)  # float worked, try int
  31.             except ValueError:  # either float or int cast failed
  32.                 pass
  33.             if value or value is 0:  # if float worked, we will have a value
  34.                 return value
  35.         print('integer or decimal input required. Please try again.')
  36.  
  37. def welcome():
  38.     print('\n\nWelcome to this simple calculator\n\n')
  39.     print('The following operators are understood:\n ')
  40.     print(*OPERATORS)
  41.     print('\nYou will be repeatedly asked to enter the operator you wish to use')
  42.     print('and the two operands to apply the operator to.\n\n')
  43.     print('To exit: just press enter/return without an operator\n\n')
  44.  
  45. welcome()
  46. while True:  # master loop, input another calculation
  47.     print()
  48.     while True:  # valid operator input
  49.         operator = input('What operation (symbol) ? ')
  50.         if not operator or operator in OPERATORS:
  51.             break
  52.         print('Sorry. Not supported.')
  53.     if not operator:
  54.         break
  55.        
  56.     num1 = get_num('enter first operand: ')
  57.     num2 = get_num('enter second operand: ')
  58.     try:
  59.         result = OPERATORS[operator](num1,num2)
  60.     except ValueError as e:
  61.         print(e)
  62.     except TypeError as e:
  63.         print(e)
  64.     except ZeroDivisionError as e:
  65.         print(e)
  66.     else:
  67.         print(f'{num1} {operator} {num2} = {result}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement