forked from yvah/pythonCalculator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
30 lines (24 loc) · 884 Bytes
/
calculator.py
File metadata and controls
30 lines (24 loc) · 884 Bytes
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
import re
class Calc:
def __init__(self, input_expression):
self.is_valid = False
self.result = None
self.expression = input_expression
def validate(self):
if not isinstance(self.expression, str):
raise TypeError
self.is_valid = not re.search('^(?:0|[1-9]\\d*)(?:[+*-](?:0|[1-9]\\d*))*$', self.expression) is None
if not self.is_valid:
raise SyntaxError('Invalid input syntax.')
def calculate(self):
self.validate()
return eval(self.expression)
def output(self):
try:
return self.calculate()
except SyntaxError as syntax_error:
return syntax_error.msg
except TypeError:
return "Wrong input type."
except Exception as error:
return f'Abnormal exit: Unexpected error has occurred ({error.msg}).'