-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.py
More file actions
67 lines (49 loc) · 1.3 KB
/
Copy pathcalculator.py
File metadata and controls
67 lines (49 loc) · 1.3 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
import argparse
import sys
def _validate(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError("Both arguments must be numeric")
def add(a, b):
_validate(a, b)
return a + b
def subtract(a, b):
_validate(a, b)
return a - b
def multiply(a, b):
_validate(a, b)
return a * b
def divide(a, b):
_validate(a, b)
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
OPERATIONS = {
"add": add,
"subtract": subtract,
"multiply": multiply,
"divide": divide,
}
def main():
parser = argparse.ArgumentParser(
prog="calculator",
description="A simple CLI calculator",
)
parser.add_argument(
"operation",
choices=OPERATIONS.keys(),
help="The operation to perform",
)
parser.add_argument("a", type=float, help="First number")
parser.add_argument("b", type=float, help="Second number")
args = parser.parse_args()
try:
result = OPERATIONS[args.operation](args.a, args.b)
print(result)
except ZeroDivisionError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
except TypeError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()