forked from robotframework/RobotDemo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.py
30 lines (25 loc) · 907 Bytes
/
calculator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Calculator(object):
BUTTONS = '1234567890+-*/C='
def __init__(self):
self._expression = ''
def push(self, button):
if button not in self.BUTTONS:
raise CalculationError("Invalid button '%s'." % button)
if button == '=':
self._expression = self._calculate(self._expression)
elif button == 'C':
self._expression = ''
elif button == '/':
self._expression += '//' # Integer division also in Python 3
else:
self._expression += button
return self._expression
def _calculate(self, expression):
try:
return str(eval(expression))
except SyntaxError:
raise CalculationError('Invalid expression.')
except ZeroDivisionError:
raise CalculationError('Division by zero.')
class CalculationError(Exception):
pass