Update calculator/operations.py
Browse files- calculator/operations.py +30 -18
calculator/operations.py
CHANGED
|
@@ -1,20 +1,32 @@
|
|
| 1 |
def perform_calculation(numbers, operation):
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
return result
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
result = numbers[0]
|
| 14 |
-
for num in numbers[1:]:
|
| 15 |
-
result /= num
|
| 16 |
-
return result
|
| 17 |
-
except ZeroDivisionError:
|
| 18 |
-
return "Error: Division by zero!"
|
| 19 |
-
else:
|
| 20 |
-
return "Unsupported operation!"
|
|
|
|
| 1 |
def perform_calculation(numbers, operation):
|
| 2 |
+
try:
|
| 3 |
+
# Handle operations based on the operation type
|
| 4 |
+
if operation == "add":
|
| 5 |
+
return sum(numbers)
|
| 6 |
+
elif operation == "subtract":
|
| 7 |
+
return numbers[0] - sum(numbers[1:])
|
| 8 |
+
elif operation == "multiply":
|
| 9 |
+
return multiply(numbers)
|
| 10 |
+
elif operation == "divide":
|
| 11 |
+
return divide(numbers)
|
| 12 |
+
else:
|
| 13 |
+
return "Error: Unsupported operation!"
|
| 14 |
+
except Exception as e:
|
| 15 |
+
return f"Error: {str(e)}"
|
| 16 |
+
|
| 17 |
+
# Helper function for multiplication
|
| 18 |
+
def multiply(numbers):
|
| 19 |
+
result = 1
|
| 20 |
+
for num in numbers:
|
| 21 |
+
result *= num
|
| 22 |
+
return result
|
| 23 |
+
|
| 24 |
+
# Helper function for division with ZeroDivisionError handling
|
| 25 |
+
def divide(numbers):
|
| 26 |
+
try:
|
| 27 |
+
result = numbers[0]
|
| 28 |
+
for num in numbers[1:]:
|
| 29 |
+
result /= num
|
| 30 |
return result
|
| 31 |
+
except ZeroDivisionError:
|
| 32 |
+
return "Error: Division by zero!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|