forked from gen-ai-py/AICrafter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex.py
50 lines (41 loc) · 1.29 KB
/
ex.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Operation:
"""Abstract operation class"""
def execute(self, num1, num2):
pass
class Add(Operation):
def execute(self, num1, num2):
return num1 + num2
class Subtract(Operation):
def execute(self, num1, num2):
return num1 - num2
class Multiply(Operation):
def execute(self, num1, num2):
return num1 * num2
class Divide(Operation):
def execute(self, num1, num2):
if num2 == 0:
raise ValueError("Cannot divide by zero!")
return num1 / num2
class OperationFactory:
"""Factory to create operation objects"""
@staticmethod
def get_operation(operator):
if operator == '+':
return Add()
elif operator == '-':
return Subtract()
elif operator == '*':
return Multiply()
elif operator == '/':
return Divide()
else:
raise ValueError(f"Invalid operator {operator}")
def calculator():
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
operation = OperationFactory.get_operation(operator)
result = operation.execute(num1, num2)
print(f"The result is: {result}")
if __name__ == "__main__":
calculator()