-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
76 lines (55 loc) · 1.41 KB
/
calculator.py
File metadata and controls
76 lines (55 loc) · 1.41 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
__author__ = 'syedaali'
# simple calculator
# input should be in format # <opr> #
# opr should be one of +,-,/,*
# run as: python calculator.py
import re
def add(x, y):
return (x) + (y)
def subtract(x, y):
return (x) - (y)
def multiply(x, y):
return (x) * (y)
def divide(x, y):
try:
return (x) / (y)
except ZeroDivisionError:
return "Cannot divide by zero"
def decide(num_list):
a = float(num_list[0])
b = float(num_list[2])
if num_list[1] == '+':
print add(a, b)
elif num_list[1] == '-':
print subtract(a, b)
elif num_list[1] == '*':
print multiply(a, b)
elif num_list[1] == '/':
print divide(a, b)
else:
print 'I do not understand, bye'
exit(1)
def work():
user_input = raw_input("Expecting # +|-|/|* #: ")
user_input.strip("\n")
calculate = re.sub('\s+', '', user_input)
if calculate == 'q':
print 'bye'
exit(0)
# use http://pythex.org/ for checking regex
pattern = re.compile(
r"""^(?P<first>\d+)
(?P<opr>\+|\-|\*|\/)
(?P<second>\d+)$""",
re.VERBOSE)
match = re.search(pattern, calculate)
if match:
num_list = match.group('first'), match.group(
'opr'), match.group('second')
decide(num_list)
else:
print 'expecting <num><opr><num>'
def main():
while (1):
work()
main()