Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ''' simple console based calculator '''
- import operator as op
- OPERATORS = {
- '**': op.pow,
- '^' : op.pow,
- '*' : op.mul,
- '/' : op.truediv,
- '//': op.floordiv,
- '+' : op.add,
- '-' : op.sub,
- '%' : op.mod,
- '<' : op.lt,
- '<=': op.le,
- '==': op.eq,
- '!=': op.ne,
- '>=': op.ge,
- '>' : op.gt,
- }
- def get_num(msg):
- ''' promt for and return numeric input - reject responses that are not integer or float '''
- while True:
- response = input(msg)
- value = None
- if response:
- try:
- value = float(response)
- value = int(response) # float worked, try int
- except ValueError: # either float or int cast failed
- pass
- if value or value is 0: # if float worked, we will have a value
- return value
- print('integer or decimal input required. Please try again.')
- def welcome():
- print('\n\nWelcome to this simple calculator\n\n')
- print('The following operators are understood:\n ')
- print(*OPERATORS)
- print('\nYou will be repeatedly asked to enter the operator you wish to use')
- print('and the two operands to apply the operator to.\n\n')
- print('To exit: just press enter/return without an operator\n\n')
- welcome()
- while True: # master loop, input another calculation
- print()
- while True: # valid operator input
- operator = input('What operation (symbol) ? ')
- if not operator or operator in OPERATORS:
- break
- print('Sorry. Not supported.')
- if not operator:
- break
- num1 = get_num('enter first operand: ')
- num2 = get_num('enter second operand: ')
- try:
- result = OPERATORS[operator](num1,num2)
- except ValueError as e:
- print(e)
- except TypeError as e:
- print(e)
- except ZeroDivisionError as e:
- print(e)
- else:
- print(f'{num1} {operator} {num2} = {result}')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement