Advertisement
gruntfutuk

Calcsimple

Aug 15th, 2018
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 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 as e:  # 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. print('\n\nWelcome to this simple calculator\n\n')
  38. print('The following operators are understood:\n ')
  39. print('  '.join(OPERATORS))
  40. print('\nYou will be repeatedly asked to enter the operator you wish to use')
  41. print('and the two operands to apply the operator to. To exit the programme')
  42. print('simply press enter/return on its own when prompted for an operator.\n\n')
  43.  
  44. while True:  # master loop, input another calculation
  45.     print()
  46.     while True:  # valid operator input
  47.         operator = input('What operation (symbol) ? ')
  48.         if not operator or operator in OPERATORS:
  49.             break
  50.         print('Sorry. Not supported.')
  51.     if not operator:
  52.         break
  53.        
  54.     num1 = get_num('enter first operand: ')
  55.     num2 = get_num('enter second operand: ')
  56.     try:
  57.         result = OPERATORS[operator](num1,num2)
  58.     except ValueError as e:
  59.         print(e)
  60.     except TypeError as e:
  61.         print(e)
  62.     except ZeroDivisionError as e:
  63.         print(e)
  64.     else:
  65.         print(f'{num1} {operator} {num2} = {result}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement